<hibernate-mapping ><class name="mypack.Company" table="COMPANIES" ><id name="id" type="long" column="ID"><generator class="increment"/></id><PRoperty name="name" type="string" column="NAME" /><set name="employees"inverse="true"lazy="true" ><key column="COMPANY_ID" /><one-to-many class="mypack.Employee" /></set> </class></hibernate-mapping>
<hibernate-mapping > <class name="mypack.Employee" table="EMPLOYEES"> <id name="id" type="long" column="ID"> <generator class="increment"/> </id> <discriminator column="EMPLOYEE_TYPE" type="string" /> <property name="name" type="string" column="NAME" /> <many-to-one name="company" column="COMPANY_ID" class="mypack.Company" /> <subclass name="mypack.HourlyEmployee" discriminator-value="HE" > <property name="rate" column="RATE" type="double" /> </subclass> <subclass name="mypack.SalariedEmployee" discriminator-value="SE" > <property name="salary" column="SALARY" type="double" /> </subclass> </class> </hibernate-mapping>
Configuration config = new Configuration();config.addClass(Company.class).addClass(Employee.class);
<class name="mypack.Employee" table="EMPLOYEES" discriminator-value="EE">
List employees=session.find("from Employee");
List hourlyEmployees=session.find("from HourlyEmployee");
ant -file build2.xml run
findAllHourlyEmployees():检索数据库中所有的HourlyEmployee对象。 findAllEmployees():检索数据库中所有的Employee对象。 loadCompany():加载一个Company对象。 saveEmployee():保存一个Employee对象。
tx = session.beginTransaction();List results=session.find("from HourlyEmployee");tx.commit();return results;在运行Session的find()方法时,Hibernate执行以下select语句:select * from EMPLOYEES where EMPLOYEE_TYPE='HE' ;select * from COMPANIES where ID=1;
tx = session.beginTransaction();List results=session.find("from Employee");tx.commit();return results;在运行Session的find()方法时,Hibernate执行以下select语句:
select * from EMPLOYEES;select * from COMPANIES where ID=1;
tx = session.beginTransaction();Company company=(Company)session.load(Company.class,new Long(id));Hibernate.initialize(company.getEmployees());tx.commit();
tx = session.beginTransaction();session.save(employee);tx.commit();
Employee employee=new HourlyEmployee("Mary",300,company);saveEmployee(employee);
insert into EMPLOYEES(ID,NAME,RATE,EMPLOYEE_TYPE,CUSTOMER_ID)values(5, 'Mary ',300, 'HE',1);
(出处:http://www.VeVb.com)
新闻热点
疑难解答