Hibernate中的一对一注解配置
Posted 会飞的豆子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hibernate中的一对一注解配置相关的知识,希望对你有一定的参考价值。
Card类
package cn.OneToOne2017109.entity; import javax.persistence.*; /** * Created by YSS on 2017/10/9. */
@Entity
@Table(name = "Card")
public class Card {
@Id
@GeneratedValue
private Integer cid;
@Column
private String cnum;
@OneToOne(mappedBy = "card",cascade = CascadeType.ALL)
private People people;
public Integer getCid() {
return cid;
}
public void setCid(Integer cid) {
this.cid = cid;
}
public String getCnum() {
return cnum;
}
public void setCnum(String cnum) {
this.cnum = cnum;
}
public People getPeople() {
return people;
}
public void setPeople(People people) {
this.people = people;
}
}
People类
@Entity @Table(name = "People") public class People { @Id @GeneratedValue private Integer pid; @Column private String pname; @OneToOne @JoinColumn(name = "cid") private Card card; public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public Card getCard() { return card; } public void setCard(Card card) { this.card = card; } }
测试类
public class testonetoone { Configuration cfg; SessionFactory factory; Session session; Transaction tx; @Before public void mybefor(){ cfg=new Configuration().configure(); factory=cfg.buildSessionFactory(); session=factory.openSession(); tx=session.beginTransaction(); } @After public void myafter(){ tx.commit(); } @Test public void test03() { People people=new People(); Card card=new Card(); people.setPname("123"); card.setCnum("123133"); card.setPeople(people); people.setCard(card); session.save(card); } }
将大配置中的mapping节点改为
<mapping class=" "/>
以上是关于Hibernate中的一对一注解配置的主要内容,如果未能解决你的问题,请参考以下文章
java hibernate注解映射类的字段可以和数据库中的字段不一致吗