码迷,mamicode.com
首页 > Web开发 > 详细

Hibernate注解

时间:2016-08-23 18:33:28      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

一、什么是注解?

  解析:来源:Hibernate提供了Hibernate Annotations扩展包,它可以替换复杂的hbm.xml文件( Annotations扩展包是hibernate-annotation-3.4.0GA.zip)

     作用:使得Hibernate程序的开发大大的简化。利用注解后,可不用定义持久化类对应的*.hbm.xml,而直接以注解方式写入持久化类的实现中。

二、注解配置持久化类常用注解。

      注解                   含义和作用              
  @Entity   将 一个类声明为一个持久化类
  @Id   声明了持久化类的标识属性(相当于数据表的主键)
  @GeneratedValue   定义标识属性值的生成策略
  @Table   为持久化类映射指定表(table)、目录(catalog)和schema的名称。默认值,持久化类名,不带包名
  @UniqueConstraint   定义表的唯一约束
  @Lob   表示属性将被持久化为Blob或者Clob类型
  @Column   将属性映射到列
  @Transient   忽略这些字段和属性,不用持久化到数据库

 

三、注解配置对象关联关系

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

场景一:一个学生对应一个身份证号(一对一关联;注意看举例子的注释)

Student类

关键代码:

   //在底层的Student数据表中植入的列名

    @JoinColumn(name="cid")//关联外键

package cn.happy.entity_sql;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

/**
 * 学生对卡    一对一关联
 * */
@Entity
@Table(name="Student")
public class Student {
    //表示属性
    @Id
    //使用默认的序列
    @GeneratedValue
    private Integer id;
    @Column(name="StuName")
    private String stuName;
    //一对一关联   保存学生的时候自动保存身份对象
    @OneToOne(cascade={CascadeType.ALL})
    //在底层的Student数据表中植入的列名
    @JoinColumn(name="cid")//关联外键
    
    private IdCard cardid;
    
    
    public Student(Integer id, String stuName, IdCard cardid) {
        super();
        this.id = id;
        this.stuName = stuName;
        this.cardid = cardid;
    }
    public Student() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getStuName() {
        return stuName;
    }
    public void setStuName(String stuName) {
        this.stuName = stuName;
    }
    public IdCard getCardid() {
        return cardid;
    }
    public void setCardid(IdCard cardid) {
        this.cardid = cardid;
    }
    
}

 

Idcard类

关键代码:

  //mappedBy 表示由craid所在的对象维护关联关系

  @OneToOne(mappedBy="cardid")

package cn.happy.entity_sql;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

/**
 * IdCard身份证
 * */
@Entity
@Table(name="IdCard")
public class IdCard {
    @Id
    //限制长度为18位,相当于约束
    @Column(length=18)
    private String cid;
    @Column(name="cname")
    private String carName;
    //mappedBy 表示由craid所在的对象维护关联关系
    @OneToOne(mappedBy="cardid")
    private Student stu;
    
    
    public IdCard(String cid, String carName, Student stu) {
        super();
        this.cid = cid;
        this.carName = carName;
        this.stu = stu;
    }
    public IdCard() {
        super();
        // TODO Auto-generated constructor stub
    }
    public String getCid() {
        return cid;
    }
    public void setCid(String cid) {
        this.cid = cid;
    }
    public String getCarName() {
        return carName;
    }
    public void setCarName(String carName) {
        this.carName = carName;
    }
    public Student getStu() {
        return stu;
    }
    public void setStu(Student stu) {
        this.stu = stu;
    }
    
    
    
}

测试类

package cn.happy.test;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.happy.entity_sql.IdCard;
import cn.happy.entity_sql.Student;
import cn.happy.until.HibernateUtil;

public class OneToOne_wgy {
@Test
public void GetGood(){
    Session session = HibernateUtil.currentSession();
    Transaction tx = session.beginTransaction();
    Student stu=new Student();
    stu.setStuName("聆听心跳的旋律");
    
    IdCard cid=new IdCard();
    cid.setCid("123321311111111111"); 
    stu.setCardid(cid);
    
    session.save(cid);
    session.save(stu);
    
    tx.commit();
    HibernateUtil.closeSession();
}
}

 (二)@OneToMang  and @MangToOne(建立双向关联一对多多对一)

场景一:一个部门对应多个员工;多个员工对应一个部门

Emp类

package cn.happy.entity.one;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 * 1.2 员工类
 * @author happy
 *
 */
@Entity
@Table
public  class Emp {
    @Id
   private Integer empId;
    @Column
   private String empName;
   
   
   @ManyToOne
   @JoinColumn(name="deptNo")
   private Dept dept;
   
    public Integer getEmpId() {
        return empId;
    }
    public void setEmpId(Integer empId) {
        this.empId = empId;
    }
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
    public Dept getDept() {
        return dept;
    }
    public void setDept(Dept dept) {
        this.dept = dept;
    }
}

 Dept类

 

package cn.happy.entity.one;
import java.util.HashSet;
import java.util.Set;
  //jpa注解
import javassist.expr.NewArray;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.GenericGenerators;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;

/**
 * 1.1 部门表    uuid  guid  全球唯一编码    自增列    序列   32位16进制数
 * 
 * @author happy
 * 
 */
   //Dept部门类可以被HIbernate进行管理
    @Entity
    @Table(name="Dept")
    public class Dept {
        @Id
        //引用生成器
        @GeneratedValue
        private Integer deptNo;
        
        //默认Hibernate管理
        private String deptName;

        @OneToMany(mappedBy="dept")
        @LazyCollection(LazyCollectionOption.FALSE)
        private Set<Emp> emps=new HashSet<Emp>();
        
        public Set<Emp> getEmps() {
            return emps;
        }

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

        public Integer getDeptNo() {
            return deptNo;
        }
    
        public void setDeptNo(Integer deptNo) {
            this.deptNo = deptNo;
        }
    
        public String getDeptName() {
            return deptName;
        }
    
        public void setDeptName(String deptName) {
            this.deptName = deptName;
        }
    
    }

 

测试类

package cn.happy.entity.one;


import org.hibernate.Session;
import org.hibernate.Transaction;

import cn.happy.entity.Dept;
import cn.happy.entity.Emp;
import cn.happy.until.HibernateUtil;


public class mangoneonemang {

    public static void main(String[] args) {
        Session session = HibernateUtil.currentSession();
        Transaction tx = session.beginTransaction();
        
//        Dept dept = (Dept)session.load(Dept.class, 21);
//        
//        System.out.println(dept.getDeptName());
        
        
        Emp emp = (Emp)session.load(Emp.class, 21);
        
        System.out.println(emp.getEmpName());
        
        tx.commit();
        HibernateUtil.closeSession();
        
        
    }
    
    
    
}

 

 

 (三)@MangToMang(建立双向关联一对多多对一)

场景一:一个员工对应多个项目;一个项目对应多个员工(多对多的关联)

Employee类

关键代码解读:

  //准备的第三张表就是员工和项目的关系

    @JoinTable(
            name="Myproemp",//表的名字
            joinColumns=@JoinColumn(name="empid"),//emp员工和第三表的外键关系
            inverseJoinColumns=@JoinColumn(name="proid")//Project员工和第三表的外键关系
    )
package entity;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

/*
 * 员工表
 * */
@Entity
@Table(name="MyEmployee")
public class Employee {
    @Id
    @GeneratedValue
    private Integer empid;//员工编号
    private String empname;//员工名称
    //准备一个项目集合
    @ManyToMany(cascade=CascadeType.ALL)
    
    //准备的第三张表就是员工和项目的关系
    @JoinTable(
            name="Myproemp",//表的名字
            joinColumns=@JoinColumn(name="empid"),//emp员工和第三表的外键关系
            inverseJoinColumns=@JoinColumn(name="proid")//Project员工和第三表的外键关系
    )
    private Set<Project> pros=new HashSet<Project>();
    
    
    public Set<Project> getPros() {
        return pros;
    }
    public void setPros(Set<Project> pros) {
        this.pros = pros;
    }
    
    public Employee(String empname) {
        super();
        this.empname = empname;
    }
    public Employee(Integer empid, String empname) {
        this.empid = empid;
        this.empname = empname;
    }
    public Employee() {
    }
    public Integer getEmpid() {
        return empid;
    }
    public void setEmpid(Integer empid) {
        this.empid = empid;
    }
    public String getEmpname() {
        return empname;
    }
    public void setEmpname(String empname) {
        this.empname = empname;
    }
    
}

 

project类

关键代码:

   //声明员工集合

  @ManyToMany(mappedBy="pros")//将控制权交由员工

package entity;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

/*
 * 项目表
 * */
@Entity
@Table(name="MyProject")
public class Project {
    @Id
    @GeneratedValue
    private Integer proid;//项目编号
    private String proname;//项目名称
    //声明员工集合
//    @ManyToMany(mappedBy="pros")//将控制权交由员工
    @ManyToMany(mappedBy="pros")
    private Set<Employee> emps=new HashSet<Employee>();
    
    
    public Set<Employee> getEmps() {
        return emps;
    }
    public void setEmps(Set<Employee> emps) {
        this.emps = emps;
    }
    
    
    public Project(String proname) {
        this.proname = proname;
    }
    public Integer getProid() {
        return proid;
    }
    public void setProid(Integer proid) {
        this.proid = proid;
    }
    public String getProname() {
        return proname;
    }
    public void setProname(String proname) {
        this.proname = proname;
    }
    public Project(Integer proid, String proname) {
        this.proid = proid;
        this.proname = proname;
    }
    public Project() {
    }
}

 

测试类

package test;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import util.HibernateUtil;
import entity.Employee;
import entity.Project;
/*
 * 多对多关系
 * */
public class Test {
    public static void main(String[] args) {
        //查询
        //select();
        //添加数据
        innesrt();
    }
    
    //添加数据
    public static void innesrt(){
        //获取Session 
        Session session=HibernateUtil.currentSession();
        
        //开启事务
        Transaction tx = session.beginTransaction();
        //构建两个项目
        Project pro1=new Project("项目一");
        Project pro2=new Project("项目二");
        //构建多个员工
        Employee emp1=new Employee("巴黎的雨季");
        Employee emp2=new Employee("盛夏的果实");
    
        //关系交由员工处理
        
        emp1.getPros().add(pro1);
        emp1.getPros().add(pro2);
        
        emp2.getPros().add(pro2);
        
        //保存
        session.save(emp1);
        session.save(emp2);
    
        
        //提交事务
        tx.commit();
        //关闭连接
        HibernateUtil.closeSession();
    }
    
    
    //查询数据
    public static void select(){
        //获取Session 
        Session session=HibernateUtil.currentSession();
        
        //开启事务
        Transaction tx = session.beginTransaction();
        String hql="from Project";
        List<Project> list = session.createQuery(hql).list();
        for (Project item : list) {
            System.out.println(item.getProname()+item.getProid());
            for (Employee emp : item.getEmps()) {
                System.out.println(emp.getEmpid()+emp.getEmpname());
            }
        }
        //Project pro = (Project)session.get(Project.class, 3);
        //System.out.println(pro.getProname());
        //提交事务
        tx.commit();
        //关闭连接
        HibernateUtil.closeSession();
    }
    
    
    
}

 

    

 

Hibernate注解

标签:

原文地址:http://www.cnblogs.com/yejiaojiao/p/5800077.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!