首页 > 代码库 > hibernate关于一对一注解配置

hibernate关于一对一注解配置

注解(Annotation),也叫元数据。一种代码级别的说明。它是JDK1.5及以后版本引入的一个特性,与类、接口、枚举是在同一个层次。它可以声明在包、类、字段、方法、局部变量、方法参数等的前面,用来对这些元素进行说明,注释。

Emp实体类配置

@Entity
@Table(name = "Emp2")
public class Emp {
    @Id
    @GeneratedValue
    private Integer eid;
    private String ename;
    @OneToOne
    @JoinColumn(name = "did")
    private Dept dept;


    public Integer getEid() {
        return eid;
    }

    public void setEid(Integer eid) {
        this.eid = eid;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public Dept getDept() {
        return dept;
    }

    public void setDept(Dept dept) {
        this.dept = dept;
    }
}

Idcard实体类配置

@Entity
@Table(name = "Dept2")
public class Dept {
    @Id
    @GeneratedValue
    private Integer did;
    private String dname;
    @OneToOne(mappedBy = "dept",cascade = CascadeType.ALL)
    private Emp emps;

    public Emp getEmps() {
        return emps;
    }

    public void setEmps(Emp emps) {
        this.emps = emps;
    }

    public Integer getDid() {
        return did;
    }

    public void setDid(Integer did) {
        this.did = did;
    }

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }
}

hibernate.cfg.xml文件配置(需要指定标示实体类)

<mapping class="cn.wyd.a.Dept"/>
		<mapping class="cn.wyd.a.Emp"/>

测试类方法

@Test
    public void test1(){
        Emp emp=new Emp();
        Dept dept=new Dept();
        emp.setEname("123");
        dept.setDname("321");
        dept.setEmps(emp);
        emp.setDept(dept);
        session.save(dept);
    }

  

hibernate关于一对一注解配置