Student.java
packagecom.model;
publicclassStudent {
privatePKStudentpk;
privateStringsex;
publicPKStudent getPk() {
returnpk;
}
publicvoidsetPk(PKStudent pk) {
this.pk= pk;
}
publicString getSex() {
returnsex;
}
publicvoidsetSex(String sex) {
this.sex= sex;
}
}
PKStudent.java
packagecom.model;
importjava.io.Serializable;
publicclassPKStudentimplementsSerializable{
privateintid;
publicintgetId() {
returnid;
}
publicvoidsetId(intid) {
this.id= id;
}
publicString getName() {
returnname;
}
publicvoidsetName(String name) {
this.name= name;
}
privateStringname;
}
StudentTest.java
packagecom.model;
importorg.hibernate.HibernateException;
importorg.hibernate.Session;
importorg.hibernate.SessionFactory;
importorg.hibernate.cfg.Configuration;
//import org.hibernate.cfg.Configuration;
importorg.junit.AfterClass;
importorg.junit.BeforeClass;
importorg.junit.Test;
publicclassStudentTest {
privatestaticSessionFactorysf=null;
@BeforeClass
publicstaticvoidbeforeClass()
{
try{
sf=(newConfiguration()).configure().buildSessionFactory();
}catch(HibernateException e) {
//TODOAuto-generated catch block
e.printStackTrace();
}
}
@Test
publicvoidtestStudentSave()
{ PKStudent pk=newPKStudent();
pk.setId(1);
pk.setName("南山");
Student s=newStudent();
s.setPk(pk);
s.setSex("女");
Session session=sf.openSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
session.close();
// sf.close();
}
@AfterClass
publicstaticvoidafterClass()
{
sf.close();
}
}
Student.hbm.xml
hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
注意:中name=”pk”一定要写,否则会报错;也不能写成其他的值,因为在Student.java中设置联合主键为pk。中的name也不能写成student。
参考文档:中name(optional): the fully qualified Java class name of the persistent class or interface. If this attribute is missing, it is assumed that the mapping is for a non-POJO entity.
由此可见,name是作为类名的。
hibernate.cfg.xml
hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
com.mysql.jdbc.Driver
jdbc:mysql://localhost/hibernate
root
huangjing
1
org.hibernate.dialect.MySQLDialect
thread
org.hibernate.cache.NoCacheProvider
true
update
注意:联合主键中作为主键类,一定要实现serializable类。