联合主键--xml
需求:? 在T_STUDENTS表中 要将ID和NAME联合作为主键:
?
1.将id和name属性定义到一个主键类中:StudentPK 并重写hashCode()和equals()方法同时要继承Serializable接口
?
?
?
4.定义配置文件:Hibernate.cfg.xml? 略
?
?5.测试用例:
package com.zchen.hibernate.sxt.test;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.AnnotationConfiguration;import org.junit.AfterClass;import org.junit.BeforeClass;import org.junit.Test;import com.zchen.hibernate.sxt.domain.StudentPK;import com.zchen.hibernate.sxt.domain.Students;public class StudentsTest {private static SessionFactory sf = null;@BeforeClasspublic static void beforeClass(){try {sf = new AnnotationConfiguration().configure().buildSessionFactory();} catch (HibernateException e) {e.printStackTrace();}}@Testpublic void addStduentTest(){StudentPK pk = new StudentPK();pk.setId(1);pk.setName("zchen");Students s = new Students();s.setAge(24);s.setAddress("北京");s.setPk(pk);Session session = sf.getCurrentSession();session.beginTransaction();session.save(s);session.getTransaction().commit();}@AfterClasspublic static void afterClass(){if(sf != null){try {sf.close();} catch (HibernateException e) {e.printStackTrace();}}}}?
?
输出语句:
11:32:09,818? INFO SchemaExport:226 - Running hbm2ddl schema export
11:32:09,821 DEBUG SchemaExport:242 - import file not found: /import.sql
11:32:09,821? INFO SchemaExport:251 - exporting generated schema to database
11:32:09,822 DEBUG SchemaExport:377 - drop table if exists T_STUDENTS
11:32:09,879 DEBUG SchemaExport:377 - create table T_STUDENTS (ID integer not null, NAME varchar(255) not null, AGE integer, ADDRESS varchar(255), primary key (ID, NAME))
11:32:09,953? INFO SchemaExport:268 - schema export complete
Hibernate: insert into T_STUDENTS (AGE, ADDRESS, ID, NAME) values (?, ?, ?, ?)?