Hibernate 零配置Annotation注解

  JPA规范推荐使用Annotation来管理实体类与数据表之间的映射关系,从而避免同时维护两份文件(Java 实体类 和 XML 映射文件),将映射信息(写在Annotation中)与实体类集中在一起。 

   主要将替换复杂的hbm.xml文件简化Hibernate程序开发

   注解配置实体类

  

package com.hlx.annotation;

import java.io.Serializable;
import java.sql.Blob;
import java.sql.Clob;
import java.util.Date;

import javax.annotation.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

import org.hibernate.annotations.GenericGenerator;

//http://blog.csdn.net/yuanmuxingchen/article/details/48416611

@Entity
@Table(name="s_student",catalog="SCOTT")  //可以不写!
//@NamedQuery(name="all",query="from Student")  //配置命名查询 hql
//写多个必须是数组; 配置命名查询 hql
@NamedQueries({@NamedQuery(name="findByName",query="from Student where name=:my"),@NamedQuery(name="all",query="from Student") })
public class Student implements Serializable {
	
	//全部写在字段上,要么全部写在get方法上!
	@Id
//	@GeneratedValue(strategy=GenerationType.AUTO)  //自动序列hibernate;
	
	//自己创建的序列名称sequenceName = "seq_uid"
	//而并非数据库中定义的sequence来处理。必须加allocationSize=1,initialValue=1这两项配置才可以解决
	@SequenceGenerator(name = "sequenceGenerator",allocationSize=1,initialValue=1, sequenceName = "seq_uid")
	@GeneratedValue(generator="sequenceGenerator",strategy=GenerationType.SEQUENCE)
	private Integer sid;
	
	@Column(name="sname",length=20,nullable=false)
	private String name;
	
	@Column(name="sage")
	private Integer age;
	
	@Temporal(TemporalType.TIMESTAMP)   //年月日时分秒
	private Date birthday;
	
	@Column(name="smoney")
	private Double money;
	
	@Transient     //不持久化
	private String address;
	
	@Lob     //处理大字节
	private Blob music;
	
	@Lob    //处理大字节
	private Clob image;

	public Integer getSid() {
		return sid;
	}

	public void setSid(Integer sid) {
		this.sid = sid;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	public Double getMoney() {
		return money;
	}

	public void setMoney(Double money) {
		this.money = money;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Blob getMusic() {
		return music;
	}

	public void setMusic(Blob music) {
		this.music = music;
	}

	public Clob getImage() {
		return image;
	}

	public void setImage(Clob image) {
		this.image = image;
	}

	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Student(Integer sid, String name, Integer age, Date birthday,
			Double money, String address, Blob music, Clob image) {
		super();
		this.sid = sid;
		this.name = name;
		this.age = age;
		this.birthday = birthday;
		this.money = money;
		this.address = address;
		this.music = music;
		this.image = image;
	}

	public Student(String name, Integer age, Double money) {
		super();
		this.name = name;
		this.age = age;
		this.money = money;
	}

	@Override
	public String toString() {
		return "Student [sid=" + sid + ", name=" + name + ", age=" + age
				+ ", birthday=" + birthday + ", money=" + money + ", address="
				+ address + ", music=" + music + ", image=" + image + "]";
	}

	
	
	
}

注解配置对象关联关系


Dept部门表 ==》Emp员工表 oneToMany

package com.hlx.onetomany;

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

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;

/**
 * Dept entity. @author MyEclipse Persistence Tools
 */

@Entity
public class Dept implements java.io.Serializable {

	// Fields

	@Id   //PK
	@SequenceGenerator(name = "sequenceGenerator",allocationSize=1,initialValue=1, sequenceName = "seq_uid")
	@GeneratedValue(generator="sequenceGenerator",strategy=GenerationType.SEQUENCE)
	private Short deptno;
	private String dname;
	private String loc;
	//注意:注解时必须是泛型集合!!
//	 --->  OneToMany指定了一对多的关系,mappedBy="dept"指定了由多的那一方来维护关联关系,mappedBy指的是多的一方对1的这一方的依赖的属性,(注意:如果没有指定由谁来维护关联关系,则系统会给我们创建一张中间表)
	@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY,mappedBy="dept")
	private Set<Emp> emps = new HashSet<Emp>(0);

	// Constructors

	/** default constructor */
	public Dept() {
	}

	
 Emp员工表==》Dept部门表 manyToOne

package com.hlx.onetomany;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * Emp entity. @author MyEclipse Persistence Tools
 */

@Entity
//@NamedQuery(name="find1",query="from Emp  e where e.dept.deptno=?")
@NamedQuery(name="find1",query="from Emp  e where e.dept.dname=?")
public class Emp implements java.io.Serializable {

	// Fields

	@Id   //PK
	@GeneratedValue(strategy=GenerationType.AUTO)  //hibernate自动生成序列
	private Integer empno;
	
	// ---> ManyToOne指定了多对一的关系,fetch=FetchType.LAZY属性表示在多的那一方通过延迟加载的方式加载对象(默认不是延迟加载)
	@ManyToOne(fetch=FetchType.LAZY)
//	--->  通过 JoinColumn 的name属性指定了外键的名称 deptno (注意:如果我们不通过JoinColum来指定外键的名称,系统会给我们声明一个名称)
	@JoinColumn(name="deptno")
	private Dept dept;
	private Double comm;
	private String ename;
	
	@Temporal(TemporalType.DATE) //年月日
	private Date hiredate;
	private String job;
	private Integer mgr;
	private Double sal;

	// Constructors

	/** default constructor */
	public Emp() {
	}

	/** full constructor */
	public Emp(Dept dept, Double comm, String ename, Date hiredate,
			String job, Integer mgr, Double sal) {
		this.dept = dept;
		this.comm = comm;
		this.ename = ename;
		this.hiredate = hiredate;
		this.job = job;
		this.mgr = mgr;
		this.sal = sal;
	}

	// Property accessors

	public Integer getEmpno() {
		return this.empno;
	}

	public void setEmpno(Integer empno) {
		this.empno = empno;
	}

	public Dept getDept() {
		return this.dept;
	}

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

	public Double getComm() {
		return this.comm;
	}

	public void setComm(Double comm) {
		this.comm = comm;
	}

	public String getEname() {
		return this.ename;
	}

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

	public Date getHiredate() {
		return this.hiredate;
	}

	public void setHiredate(Date hiredate) {
		this.hiredate = hiredate;
	}

	public String getJob() {
		return this.job;
	}

	public void setJob(String job) {
		this.job = job;
	}

	public Integer getMgr() {
		return this.mgr;
	}

	public void setMgr(Integer mgr) {
		this.mgr = mgr;
	}

	public Double getSal() {
		return this.sal;
	}

	public void setSal(Double sal) {
		this.sal = sal;
	}

	public Emp(String ename, Date hiredate, String job, Double sal) {
		super();
		this.ename = ename;
		this.hiredate = hiredate;
		this.job = job;
		this.sal = sal;
	}

	@Override
	public String toString() {
		return "Emp [empno=" + empno + ", dept=" + dept + ", comm=" + comm
				+ ", ename=" + ename + ", hiredate=" + hiredate + ", job="
				+ job + ", mgr=" + mgr + ", sal=" + sal + "]";
	}

	
	
	
	
}

测试:

public class TestOneToMany {
	
	
	@Test
	public void find3() {

		// 1.获得会话对象
		Session session = HibernateUtil.currentSession();
		// 2.开启事务
		Transaction tx = session.beginTransaction();
		
//		 List<Emp> list= session.getNamedQuery("find1").setShort(0, new Short("20")).list();
		 List<Emp> list= session.getNamedQuery("find1").setString(0, "RESEARCH").list();
		 for (Emp student : list) {
			System.out.println(student);
		}

		//
		tx.commit();
		// 3.关闭会话
		HibernateUtil.closeSession();

	}

	@Test
	public void del() {

		// 1.获得会话对象
		Session session = HibernateUtil.currentSession();

		// 事务
		Transaction tx = session.beginTransaction();

		// // 删除数据==>查询是否有这个数据
		 Dept grade = (Dept) session.get(Dept.class, new Short("86"));
		//
		// // one那方
		 session.delete(grade);

		tx.commit();

		// 3.关闭会话
		HibernateUtil.closeSession();

	}

	@Test
	public void save() {

		// 1.获得会话对象
		Session session = HibernateUtil.currentSession();

		// 事务
		Transaction tx = session.beginTransaction();

		// 添加数据
		Dept dept = new Dept("TT", "HZ");

		Emp emp1 = new Emp("mike", new Date(), "CLERK", 500D);
		Emp emp2 = new Emp("bear", new Date(), "CLERK", 1000D);

		// 添加(你包含我)
		dept.getEmps().add(emp1);
		dept.getEmps().add(emp2);

		// (我包含你)
		emp1.setDept(dept);
		emp2.setDept(dept);

		// //

		// one那方
		session.save(dept);

		tx.commit();

		// 3.关闭会话
		HibernateUtil.closeSession();

	}

}

学生表 ===》老师表  manyToMany

@Entity
public class Studentm implements java.io.Serializable {

	// Fields

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private Integer sid;
	private String sname;

//	 --->  因为多对多之间会通过一张中间表来维护两表直接的关系,所以通过 JoinTable 这个注解来声明,name就是指定了中间表的名字,
	//JoinColumns是一个 @JoinColumn类型的数组,表示的是我这方在对方中的外键名称,我方是Student,所以在对方外键的名称就是 msid,
	//inverseJoinColumns也是一个 @JoinColumn类型的数组,表示的是对方在我这放中的外键名称,对方是Teacher,所以在我方外键的名称就是 mtid
	
@ManyToMany
   @JoinTable(name="TEACHERM_STUDENTM",joinColumns={@JoinColumn(name="MSID")},inverseJoinColumns={@JoinColumn(name="mtid")}) 
	private Set<Teacherm>  teacherms= new HashSet<Teacherm>(0);

	// Constructors

	public Set<Teacherm> getTeacherms() {
		return teacherms;
	}

	public void setTeacherms(Set<Teacherm> teacherms) {
		this.teacherms = teacherms;
	}

老师表  ===》学生表 manyToMany

@Entity
public class Teacherm implements java.io.Serializable {

	// Fields
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Integer tid;
	private String tname;
	
//	--->  表示由Student那一方来进行维护
	@ManyToMany(cascade=CascadeType.ALL,mappedBy="teacherms")
	private Set<Studentm> studentms = new HashSet<Studentm>();

	// Constructors

	public Set<Studentm> getStudentms() {
		return studentms;
	}

	public void setStudentms(Set<Studentm> studentms) {
		this.studentms = studentms;
	}

测试:

public class TestManyToMany {

	@Test
	public void test2Find() {

		// 1.获得会话对象
		Session session = HibernateUtil.currentSession();

		// 事务
		Transaction tx = session.beginTransaction();

		// 删除数据==>查询是否有这个数据
		Teacherm t1 = (Teacherm) session.get(Teacherm.class, 151);

		Set<Studentm> set = t1.getStudentms();
		for (Studentm studentm : set) {
			System.out.println(studentm);

		}

		tx.commit();

		// 3.关闭会话
		HibernateUtil.closeSession();

	}

	@Test
	public void test2Del() {

		// 1.获得会话对象
		Session session = HibernateUtil.currentSession();

		// 事务
		Transaction tx = session.beginTransaction();

		// 删除数据==>查询是否有这个数据
		Teacherm t1 = (Teacherm) session.get(Teacherm.class, 148);

		// one那方
		session.delete(t1);

		tx.commit();

		// 3.关闭会话
		HibernateUtil.closeSession();

	}

	@Test
	public void test2Save() {

		// 1.获得会话对象
		Session session = HibernateUtil.currentSession();

		// 事务
		Transaction tx = session.beginTransaction();

		// 添加数据
		Teacherm t1 = new Teacherm("mike");
		Teacherm t2 = new Teacherm("john");

		Studentm st1 = new Studentm("rabbit");
		Studentm st2 = new Studentm("cat");
		Studentm st3 = new Studentm("bear");
		Studentm st4 = new Studentm("apple");

		// (你包含我)
		t1.getStudentms().add(st1);
		t1.getStudentms().add(st2);

		t2.getStudentms().add(st3);
		t2.getStudentms().add(st4);

		// (我包含你)
		st1.getTeacherms().add(t1);
		st2.getTeacherms().add(t1);
		st3.getTeacherms().add(t2);
		st4.getTeacherms().add(t2);

		// //

		// 老师方
		session.save(t1);
		session.save(t2);

		tx.commit();

		// 3.关闭会话
		HibernateUtil.closeSession();

	}

}





 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值