<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> <property name="name" type="string" column="NAME" /> <many-to-one name="company" column="COMPANY_ID" class="mypack.Company" /> <joined-subclass name="mypack.HourlyEmployee" table="HOURLY_EMPLOYEES" > <key column="EMPLOYEE_ID" /> <property name="rate" column="RATE" type="double" /> </joined-subclass> <joined-subclass name="mypack.SalariedEmployee" table="SALARIED_EMPLOYEES" > <key column="EMPLOYEE_ID" /> <property name="salary" column="SALARY" type="double" /> </joined-subclass> </class> </hibernate-mapping>
Configuration config = new Configuration();config.addClass(Company.class).addClass(Employee.class);
<hibernate-mapping ><joined-subclass name="mypack.HourlyEmployee"table="HOURLY_EMPLOYEES" extends="mypack.Employee" >…… </joined-class><hibernate-mapping >
Configuration config = new Configuration();config.addClass(Company.class).addClass(Employee.class).addClass(HourlyEmployee.class);
List hourlyEmployees=session.find("from HourlyEmployee");
ant -file build3.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 HOURLY_EMPLOYEES he inner join EMPLOYEES e on he.EMPLOYEE_ID=e.ID;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 eleft outer join HOURLY_EMPLOYEES he on e.ID=he.EMPLOYEE_IDleft outer join SALARIED_EMPLOYEES se on e.ID=se.EMPLOYEE_ID;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, COMPANY_ID) values (5, 'Mary', 1);insert into HOURLY_EMPLOYEES (EMPLOYEE_ID ,RATE) values (5, 300);
(出处:http://www.VeVb.com)
新闻热点
疑难解答