首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Hibernate的注脚

2013-10-19 
Hibernate的注解?2.打不打勾都行??三、映射两个实体类:Employee类:package org.e276.entityimport java.ut

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 {// Fieldsprivate 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;}@Overridepublic 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 {// Fieldsprivate 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 /><mapping /></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;@BeforeClasspublic static void setUpBeforeClass() throws Exception {factory = new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory();}@AfterClasspublic static void tearDownAfterClass() throws Exception {factory = null;}@Beforepublic void setUp() throws Exception {session = factory.openSession();tx = session.beginTransaction();}@Afterpublic 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);}}/** * 查询所有的员工 */@Testpublic 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();}}}

?

热点排行