java 联合主键 id_hibernate联合主键(composite-id)

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类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值