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注解映射类的字段可以和数据库中的字段不一致吗

hibernate笔记--使用注解(annotation)方式配置单(双)向多对一的映射关系

Hibernate框架学习之注解配置关系映射

Hibernate---注解一对一

hibernate 联合主键一对多用注解怎么设置?

Hibernate---注解一对多