jpa hibernate 简单配置

环境:hbiernate 4.2.16 ,

注意:

1. hibernate4.2 实现了 jpa2.0 规范,而 hibernate4.3 实现了 jpa2.1 规范,这个要和persistence配置文件统一,不然会出现问题。

2. hibernate jpa 包 和 javaEE 包 下都有 javax.persistence.* , 有冲突,必须删掉一个。 

实体类:

    这些表都是从oracle的 hr 用户中导出来的,只配置了 employee 和 department 的关联关系。

 Region.java

package com.jt.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="REGIONS",schema="hr")
public class Region implements Serializable{
 private static final long serialVersionUID = 2050774342066489506L;
 
 private Integer regionId;
 private String regionName;
 
 @Id
 @GeneratedValue(strategy=GenerationType.AUTO)
 @Column(name="region_id")
 public Integer getRegionId() {
  return regionId;
 }
 public void setRegionId(Integer regionId) {
  this.regionId = regionId;
 }
 @Column(name="region_name")
 public String getRegionName() {
  return regionName;
 }
 public void setRegionName(String regionName) {
  this.regionName = regionName;
 }
 @Override
 public String toString() {
  return "Region [regionId=" + regionId + ", regionName=" + regionName
    + "]";
 }
}

Employee.java

package com.jt.entity;
import java.io.Serializable;
import java.util.Date;
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.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="EMPLOYEES",schema="hr")
public class Employee implements Serializable{
 private static final long serialVersionUID = 1637224465679960860L;
 
 private Integer employeeId;
 private String firstName;
 private String lastName;
 private String email;
 private String phoneInt;
 private Date hireDate;
 private String jobId;
 private Double salary;
 private Double commissionPct;
 private Integer managerId;
 private Department department;
 
 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 @Column(name="employee_id")
 public Integer getEmployeeId() {
  return employeeId;
 }
 public void setEmployeeId(Integer employeeId) {
  this.employeeId = employeeId;
 }
 @Column(name="first_name")
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 @Column(name="last_name")
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 @Column
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
 @Column(name="phone_int")
 public String getPhoneInt() {
  return phoneInt;
 }
 public void setPhoneInt(String phoneInt) {
  this.phoneInt = phoneInt;
 }
 @Column(name="hire_date")
 public Date getHireDate() {
  return hireDate;
 }
 public void setHireDate(Date hireDate) {
  this.hireDate = hireDate;
 }
 @Column(name="job_id")
 public String getJobId() {
  return jobId;
 }
 public void setJobId(String jobId) {
  this.jobId = jobId;
 }
 @Column
 public Double getSalary() {
  return salary;
 }
 public void setSalary(Double salary) {
  this.salary = salary;
 }
 @Column(name="commission_pct")
 public Double getCommissionPct() {
  return commissionPct;
 }
 public void setCommissionPct(Double commissionPct) {
  this.commissionPct = commissionPct;
 }
 @Column(name="manager_id")
 public Integer getManagerId() {
  return managerId;
 }
 public void setManagerId(Integer managerId) {
  this.managerId = managerId;
 }
 @ManyToOne(fetch=FetchType.LAZY,cascade=CascadeType.ALL)
 @JoinColumn(name="department_id") // 多对一关联,指向 “一” 的外键列名
 public Department getDepartment() {
  return department;
 }
 public void setDepartment(Department department) {
  this.department = department;
 }
 @Override
 public String toString() {
  return "Employee [commissionPct=" + commissionPct + ", department="
    + department + ", email=" + email + ", employeeId="
    + employeeId + ", firstName=" + firstName + ", hireDate="
    + hireDate + ", jobId=" + jobId + ", lastName=" + lastName
    + ", managerId=" + managerId + ", phoneInt=" + phoneInt
    + ", salary=" + salary + "]";
 }
 
}

Department.java

package com.jt.entity;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
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.Table;
@Entity
@Table(name="DEPARTMENTS",schema="hr")
public class Department implements Serializable{
 private static final long serialVersionUID = -1001327680627174429L;
 
 private Integer departmentId;
 private String departmentName;
 private Integer managerId;
 private Integer locationId;
 private Set<Employee> employees = new HashSet<Employee>();
 
 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 @Column(name="department_id")
 public Integer getDepartmentId() {
  return departmentId;
 }
 public void setDepartmentId(Integer departmentId) {
  this.departmentId = departmentId;
 }
 @Column(name="department_name")
 public String getDepartmentName() {
  return departmentName;
 }
 public void setDepartmentName(String departmentName) {
  this.departmentName = departmentName;
 }
 @Column(name="manager_id")
 public Integer getManagerId() {
  return managerId;
 }
 public void setManagerId(Integer managerId) {
  this.managerId = managerId;
 }
 @Column(name="location_id")
 public Integer getLocationId() {
  return locationId;
 }
 public void setLocationId(Integer locationId) {
  this.locationId = locationId;
 }
 // 这里是一方,mappedBy 是在“多”的那方指向“一”的 属性 
 // FetchType.LAZY 是延迟加载,会发出两条sql语句,先查employee,再查department
 // FetchType.EAGER 是 发出一条sql语句,关联查询employees 和department
 @OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL,mappedBy="department")
 public Set<Employee> getEmployees() {
  return employees;
 }
 public void setEmployees(Set<Employee> employees) {
  this.employees = employees;
 }
 @Override
 public String toString() {
  return "Department [departmentId=" + departmentId + ", departmentName="
    + departmentName + ", employees.size=" + employees.size() + ", locationId="
    + locationId + ", managerId=" + managerId + "]";
 }
 
}

 

META-INF/persistence.xml 配置文件:

<?xml version="1.0" encoding="utf-8"?>

<persistence xmlns="
http://java.sun.com/xml/ns/persistence
"

 xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance
"

 xsi:schemaLocation="
http://java.sun.com/xml/ns/persistence

                     
http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/persistence_2_0.xsd
"

 version="2.0">

 <persistence-unit name="dev" transaction-type="RESOURCE_LOCAL">

  <properties>

   <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />  

            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />  

            <property name="hibernate.connection.username" value="root" />  

            <property name="hibernate.connection.password" value="root" />  

            <property name="hibernate.connection.url" value="jdbc:mysql://192.168.1.200:3306/hr" />  

<!--            <property name="hibernate.max_fetch_depth" value="3" />  -->

            <property name="hibernate.hbm2ddl.auto" value="validate" />

            <property name="hibernate.show_sql" value="true" />

            <property name="hibernate.format_sql" value="true" /> 

  </properties>

 </persistence-unit>

</persistence>

测试:

package com.jt.test;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.jt.entity.Department;
import com.jt.entity.Employee;
import com.jt.entity.Region;

public class AllTest {
 EntityManagerFactory entityManagerFactory;
 EntityManager entityManager;
 
 @Before
 public void init(){
  entityManagerFactory = 
   Persistence.createEntityManagerFactory("dev");
  entityManager = entityManagerFactory.createEntityManager();
 }
 
 @Test
 public void test1(){
  System.out.println(entityManager.getClass().getName());
 }
 
 @Test
 public void testManyToOne(){
  // 多对一测试 
  Employee employee = entityManager.find(Employee.class, 106);
  System.out.println(employee);// 重写了toString方法,同时输出 department信息 
 }
 
 @Test
 public void testOneToMany(){
  // 一对多测试 
  Department department = entityManager.find(Department.class, 60);
  System.out.println("dept_name:"+department.getDepartmentName());
  for(Employee emp : department.getEmployees()){
   System.out.println(emp.getFirstName()+' '+emp.getLastName()+','+emp.getSalary());
  }
 }
 
 @Test
 public void testFind(){
  Region region = entityManager.find(Region.class, 3);
  System.out.println(region);
 }
 
 @Test
 public void testAdd(){
  Region region = new Region();
  //region.setRegionId(5);
  region.setRegionName("moon");
  entityManager.getTransaction().begin();
  entityManager.persist(region);
  entityManager.getTransaction().commit();
 }
 
 @Test
 public void testDel(){
  Region region = entityManager.find(Region.class, 5);
  entityManager.getTransaction().begin();
  entityManager.remove(region);
  entityManager.getTransaction().commit();
 }
 
 @SuppressWarnings("unchecked")
 @Test
 public void testFindAll(){
  Query query = entityManager.createQuery("select r from Region r");
  List<Region> list = query.getResultList();
  for (Region region : list) {
   System.out.println(region);
  }
 }
 
 @After
 public void close(){
  entityManager.close();
  entityManagerFactory.close();
 }
}

你可能感兴趣的:(jpa hibernate 简单配置)