Hibernate双向一对一映射关系配置代码实例
1、外键映射
1.1、实体类
packagecom.yl.bean; importjava.io.Serializable; /** *公民实体类 */ publicclassPersonimplementsSerializable{ privateIntegerid; privateStringname; privatePersonCardcard; publicPerson(){ } publicPerson(Integerid,Stringname,PersonCardcard){ this.id=id; this.name=name; this.card=card; } publicIntegergetId(){ returnid; } publicvoidsetId(Integerid){ this.id=id; } publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ this.name=name; } publicPersonCardgetCard(){ returncard; } publicvoidsetCard(PersonCardcard){ this.card=card; } @Override publicStringtoString(){ return"Person{"+ "id="+id+ ",name='"+name+'\''+ ",card="+card+ '}'; } }
packagecom.yl.bean; importjava.io.Serializable; /** *身份证实体类 */ publicclassPersonCardimplementsSerializable{ privateIntegerid; privateStringcardNo; privatePersonperson; publicPersonCard(){ } publicPersonCard(Integerid,StringcardNo,Personperson){ this.id=id; this.cardNo=cardNo; this.person=person; } publicIntegergetId(){ returnid; } publicvoidsetId(Integerid){ this.id=id; } publicStringgetCardNo(){ returncardNo; } publicvoidsetCardNo(StringcardNo){ this.cardNo=cardNo; } publicPersongetPerson(){ returnperson; } publicvoidsetPerson(Personperson){ this.person=person; } @Override publicStringtoString(){ return"PersonCard{"+ "id="+id+ ",cardNo='"+cardNo+'\''+ ",person="+person+ '}'; } }
1.2、全局配置文件(hibernate.cfg.xml)
com.mysql.cj.jdbc.Driver jdbc:mysql://localhost:3306/hibernate?characterEncoding=utf8&serverTimezone=GMT%2B8 root 123456 true update
1.3、公民映射配置文件(Person.hbm.xml)
1.4、身份证映射配置文件(PersonCard.hbm.xml)
1.5、测试类
@Test publicvoidtest01(){ Personperson=newPerson(); person.setName("yl001"); PersonCardpersonCard=newPersonCard(); personCard.setCardNo("001"); person.setCard(personCard); personCard.setPerson(person); Sessionsession=HibernateUtils.getSession(); Transactiontransaction=session.beginTransaction(); session.save(person); session.save(personCard); transaction.commit(); session.close(); }
2、主键映射
表的字段既是主键,又是外键(eg:身份证号码既是主键又是外键)
2.1、映射配置文件实现
主要修改PersonCard.hbm.xml文件
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。