欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hibernate的注解

程序员文章站 2022-06-12 19:18:25
...

以Hibernate3.3作为例子。

 

一、常用的注解

aaa@qq.com(name = "entityName"):

必须,name为可选,对应数据库中一的个表

 

aaa@qq.com(name = "", catalog = "", schema = "") :

可选,通常和@Entity配合使用,只能标注在实体的class定义处,表示实体对应的数据库表的信息
name:可选,表示表的名称。默认表名和实体名称一致,只有在不一致的情况下才需要指定表名

catalog:可选,表示Catalog名称,默认为Catalog("")
schema:可选,表示Schema名称,默认为Schema("")

 

aaa@qq.com

必须

@Id定义了映射到数据库表的主键的属性,一个实体只能有一个属性被映射为主键,置于getXxxx()上

 

aaa@qq.com(strategy = GenerationType, generator = "")

可选

strategy:表示主键生成策略,有AUTO,INDENTITY,SEQUENCE 和 TABLE 4种,分别表示让ORM框架自动选择,根据数据库的Identity字段生成,根据数据库表的Sequence字段生成,以有根据一个额外的表生成主键,默认为AUTO

generator:表示主键生成器的名称,这个属性通常和ORM框架相关,例如Hibernate可以指定uuid等主键生成方式

 

aaa@qq.com(fetch = FetchType, optional = true)

可选

@Basic表示一个简单的属性到数据库表的字段的映射,对于没有任何标注的getXxxx()方法,默认即为@Basic
fetch:表示该属性的读取策略,有EAGER和LAZY两种,分别表示主支抓取和延迟加载,默认为EAGER
optional:表示该属性是否允许为null,默认为true

 

aaa@qq.com(name = "", unique = true, nullable = false, precision = 9, scale = 0)

可选

@Column描述了数据库表中该字段的详细定义,这对于根据JPA注解生成数据库表结构的工具非常有作用
name:表示数据库表中该字段的名称,默认情形属性名称一致
nullable:表示该字段是否允许为null,默认为true
unique:表示该字段是否是唯一标识,默认为false
length:表示该字段的大小,仅对String类型的字段有效
insertable:表示在ORM框架执行插入操作时,该字段是否应出现INSETRT语句中,默认为true
updateable:表示在ORM框架执行更新操作时,该字段是否应该出现在UPDATE语句中,默认为true。对于一经创建就不可以更改的字段,该属性非常有用,如对于birthday字段
columnDefinition:表示该字段在数据库中的实际类型.通常ORM框架可以根据属性类型自动判断数据库中字段的类型,但是对于Date类型仍无法确定数据库中字段类型究竟是DATE,TIME还是TIMESTAMP。此外,String的默认映射类型为VARCHAR,如果要将String类型映射到特定数据库的BLOB或TEXT字段类型,该属性非常有用

 

aaa@qq.com

可选

@Transient表示该属性并非一个到数据库表的字段的映射,ORM框架将忽略该属性。如果一个属性并非数据库表的字段映射,就务必将其标示为@Transient,否则,ORM框架默认其注解为@Basic

 

aaa@qq.com(fetch = FetchType, cascade = CascadeType) 

可选

@ManyToOne表示一个多对一的映射,该注解标注的属性通常是数据库表的外键
optional:是否允许该字段为null,该属性应该根据数据库表的外键约束来确定,默认为true
fetch:表示抓取策略,默认为FetchType.EAGER
cascade:表示默认的级联操作策略,可以指定为ALL、PERSIST、MERGE、REFRESH和REMOVE中的若干组合,默认为无级联操作
targetEntity:表示该属性关联的实体类型,该属性通常不必指定,ORM框架根据属性类型自动判断targetEntity

 

aaa@qq.com

可选

@JoinColumn和@Column类似,介量描述的不是一个简单字段,而一一个关联字段,例如,描述一个@ManyToOne的字段
name:该字段的名称。由于@JoinColumn描述的是一个关联字段,如ManyToOne,则默认的名称由其关联的实体决定

 

aaa@qq.com(fetch = FetchType, cascade = CascadeType) 

可选

@OneToMany描述一个一对多的关联,该属性应该为集体类型,在数据库中并没有实际字段
fetch:表示抓取策略,默认为FetchType.LAZY,因为关联的多个对象通常不必从数据库预先读取到内存
cascade:表示级联操作策略,对于OneToMany类型的关联非常重要,通常该实体更新或删除时,其关联的实体也应当被更新或删除

 

aaa@qq.com(fetch = FetchType, cascade = CascadeType) 

可选

@OneToOne描述一个一对一的关联
fetch:表示抓取策略,默认为FetchType.LAZY
cascade:表示级联操作策略

aaa@qq.com

可选

@ManyToMany描述一个多对多的关联,多对多关联上是两个一对多关联,但是在ManyToMany描述中,中间表是由ORM框架自动处理
targetEntity:表示多对多关联的另一个实体类的全名,例如:package.Book.class
mappedBy:表示多对多关联的另一个实体类的对应集合属性名称

 

aaa@qq.com

可选
@MappedSuperclass可以将超类的JPA注解传递给子类,使子类能够继承超类的JPA注解

 

aaa@qq.com

可选
@Embedded将几个字段组合成一个类,并作为整个Entity的一个属性

 

二、新建一Java Project,并搭建Hibernate3.3框架

 1.必须打勾,支持Hibernate的注解


Hibernate的注解
 

2.打不打勾都行


Hibernate的注解
 

 

三、映射两个实体类:

Employee类:

package org.e276.entity;

import java.util.Date;
import javax.persistence.Column;
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.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * Employee entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "EMPLOYEE", schema = "Y2")
public class Employee implements java.io.Serializable {

	// Fields

	private Integer id;
	private Department department;
	private String name;
	private Boolean sex;
	private Double salary;
	private Date birthday;

	// Constructors

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

	/** minimal constructor */
	public Employee(Integer id) {
		this.id = id;
	}

	/** full constructor */
	public Employee(Integer id, Department department, String name, Boolean sex, Double salary,
			Date birthday) {
		this.id = id;
		this.department = department;
		this.name = name;
		this.sex = sex;
		this.salary = salary;
		this.birthday = birthday;
	}

	// Property accessors
	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "generator")
	@SequenceGenerator(name = "generator", sequenceName = "emp_seq")
	@Column(name = "ID", unique = true, nullable = false, precision = 9, scale = 0)
	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@ManyToOne(fetch = FetchType.EAGER)
	@JoinColumn(name = "DEPART_ID")
	public Department getDepartment() {
		return this.department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}

	@Column(name = "NAME", length = 20)
	public String getName() {
		return this.name;
	}

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

	@Column(name = "SEX", precision = 1, scale = 0)
	public Boolean getSex() {
		return this.sex;
	}

	public void setSex(Boolean sex) {
		this.sex = sex;
	}

	@Column(name = "SALARY", precision = 8)
	public Double getSalary() {
		return this.salary;
	}

	public void setSalary(Double salary) {
		this.salary = salary;
	}

	@Temporal(TemporalType.DATE)
	@Column(name = "BIRTHDAY", length = 7)
	public Date getBirthday() {
		return this.birthday;
	}

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

	@Override
	public String toString() {
		return "Employee [id=" + id + ", department=" + department + ", name=" + name + ", sex="
				+ sex + ", salary=" + salary + ", birthday=" + birthday + "]";
	}
	
}

 

Department类:

package org.e276.entity;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
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.OrderBy;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import org.hibernate.annotations.Formula;

/**
 * Department entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "DEPARTMENT", schema = "Y2")
public class Department implements java.io.Serializable {

	// Fields

	private Integer id;
	private Integer count;//作为只读属性,表中没有这列
	private String name;
	private List<Employee> employees = new ArrayList<Employee>(0);

	// Constructors

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

	/** minimal constructor */
	public Department(Integer id, String name) {
		this.id = id;
		this.name = name;
	}

	/** full constructor */
	public Department(Integer id, String name, List<Employee> employees) {
		this.id = id;
		this.name = name;
		this.employees = employees;
	}

	// Property accessors
	@Id
	@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="generator")
	@SequenceGenerator(name="generator",sequenceName="depart_seq")
	@Column(name = "ID", unique = true, nullable = false, precision = 4, scale = 0)
	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@Column(name = "NAME", nullable = false, length = 20)
	public String getName() {
		return this.name;
	}

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

	@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "department")
	@OrderBy("salary desc")
	public List<Employee> getEmployees() {
		return this.employees;
	}

	public void setEmployees(List<Employee> employees) {
		this.employees = employees;
	}

	//注意前后一定要有括号,查询时是作为一列存在的子查询
	@Formula("(select count(*) from department)")
	public Integer getCount() {
		return count;
	}

	public void setCount(Integer count) {
		this.count = count;
	}

}

 

七、Hibernate的配置文件

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
	<property name="dialect">
		org.hibernate.dialect.Oracle10gDialect
	</property>
	<property name="connection.url">
		jdbc:oracle:thin:@localhost:1521:orcl
	</property>
	<property name="connection.username">y2</property>
	<property name="connection.password">bdqn</property>
	<property name="connection.driver_class">
		oracle.jdbc.driver.OracleDriver
	</property>
	<property name="myeclipse.connection.profile">Y2</property>
	<property name="show_sql">true</property>
	<property name="format_sql">true</property>
	<mapping class="org.e276.entity.Department" />
	<mapping class="org.e276.entity.Employee" />

</session-factory>

</hibernate-configuration>

 

 

八、测试类(使用了Junit 4.0):

package org.e276.test;

import java.util.Date;
import java.util.List;
import org.e276.entity.Department;
import org.e276.entity.Employee;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * 测试类
 * 
 * @author miao
 * 
 */
public class TestEmployee {

	static SessionFactory factory = null;
	private Session session;
	private Transaction tx;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		factory = new AnnotationConfiguration().configure("hibernate.cfg.xml")
				.buildSessionFactory();
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		factory = null;
	}

	@Before
	public void setUp() throws Exception {
		session = factory.openSession();
		tx = session.beginTransaction();
	}

	@After
	public void tearDown() throws Exception {
		tx.commit();
		session.close();
	}

	/**
	 * 查询部门的信息 部门名字 部门总数 员工数
	 */
	public void findDepartInfo() {
		Department department = (Department) session.get(Department.class, 3);
		// 得到部门名字
		System.out.println("部门名字是:" + department.getName());
		// 输出部门总数
		System.out.println("部门总数是:" + department.getCount());
		// 得到员工集合
		List<Employee> employees = department.getEmployees();
		// 输出员工,按工资降序排列
		for (Employee employee : employees) {
			System.out.println(employee);
		}
	}

	/**
	 * 查询所有的员工
	 */
	@Test
	public void findAllEmployee() {
		@SuppressWarnings("unchecked")
		List<Employee> employees = session.createQuery("from Employee").list();
		for (Employee employee : employees) {
			System.out.println(employee);
		}
	}

	/**
	 * 插入员工信息
	 */
	public void addEmployee() {
		Department department = (Department) session.get(Department.class, 3);
		Employee employee = new Employee();
		employee.setDepartment(department);
		employee.setName("小伙伴");
		employee.setSex(false);
		employee.setBirthday(new Date());
		employee.setSalary(3800.00);
		try {
			// 保存
			session.save(employee);
			System.out.println("添加成功!");
		} catch (HibernateException e) {
			System.out.println("添加失败!");
			e.printStackTrace();
		}
	}
}

 

相关标签: Hibernate