Hibernate一对一注解,一对多注解

使用Hibernate注解的步骤如下:

      (1)使用注解配置持久化类及对象关联关系

      (2)在Hibernate配置文件(hibernate,cfg,xml)中声明持久化类,语法如下:

               

    配置持久化类的常用注解

      @Entity   将一个类声明为一个持久化类

      @Table   为持久化类映射指定表(table),目录(catalog)和schema的名称。默认值:持久化类名,不带包名

      @Id   声明了持久化类的标识属性(相当于数据表的主键)

      @GeneratedValue   定义标识属性值的生成策略

      @UniqueConstraint    定义表的唯一约束

      @Lob   表示属性将被持久化为Blob或者Clob类型

      @Column   将属性映射到数据库字段

      @Transient   指定可以忽略的属性,不用持久化到数据库

    使用注解配置关联关系

     @OneToOne   建立持久化类之间的一对一关联关系

     @OneToMany   建立持久化类之间的一对多关联关系

     @ManyToOne   持久化类之间的多对一关联关系

     @ManyToMany   建立持久化类之间的多对多关联关系  

-----------------------------------------一对一注解-------------------------------------

   Card类

@Entity
@Table(name = "Card")
public class Card {
     @Id
     @GeneratedValue
    private Integer cid;

     @Column
     private String cname;

     @OneToOne(mappedBy = "card",cascade = CascadeType.ALL)
     private 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;
  hibernate.cfg.xml      
 
  
 <mapping class="cn.happy.zhujie.onetoone.Card"/>
 <mapping class="cn.happy.zhujie.onetoone.People"/>
  测试类
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 test01() {
    People people=new People();
    Card card=new Card();
    people.setPname("111");
    card.setCname("123133");
    card.setPeople(people);
    people.setCard(card);
    session.save(card);
}
--------------------一对多注解-----------------------------
   Dept类
@Entity
@Table(name = "Dept01")
public class Dept {
@Id
@GeneratedValue
private  Integer did;

@Column
private String deptname;
@OneToMany(mappedBy = "dept",cascade = CascadeType.ALL,fetch = FetchType.LAZY)
private  Set em=new HashSet();
  emp类 
@Entity
@Table(name = "Emp01")
public class emp {
    @Id
    @GeneratedValue
    private  Integer eid;

    @Column
    private String name;

    @ManyToOne
    @JoinColumn(name = "did")
    private  Dept  dept;
   hibernate.cfg.xml
 
  
   <mapping class="cn.happy.zhujie.onetoone.Dept"/>
   <mapping class="cn.happy.zhujie.onetoone.emp"/>
   测试类
//添加部门      一对多注解
@Test
public void  loadText(){
    Dept  dept=new Dept();
    dept.setDeptname("财务部");

    emp emps=new emp();
    emps.setName("啦啦");

    dept.getEm().add(emps);

    emps.setDept(dept);
    session.save(dept);

   // tx.commit();
    System.out.println("save ok!!");
}

你可能感兴趣的:(Hibernate一对一注解,一对多注解)