hibernate one-to-many many-to-one 双向注解

建表语句:

DROP TABLE IF EXISTS `t_company`;
CREATE TABLE `t_company` (
  `companyId` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `companyName` varchar(30) NOT NULL,
  PRIMARY KEY (`companyId`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=gb2312;

INSERT INTO `t_company` VALUES (1, Sun);
INSERT INTO `t_company` VALUES (2, Apache);

DROP TABLE IF EXISTS `t_employee`;
CREATE TABLE `t_employee` (
  `employeeId` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `employeeName` varchar(15) NOT NULL,
  `cid` int(10) unsigned NOT NULL,
  PRIMARY KEY (`employeeId`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=gb2312;

INSERT INTO `t_employee` VALUES (1, Tom, 1);
INSERT INTO `t_employee` VALUES (2, Summ, 1);
INSERT INTO `t_employee` VALUES (3, Cat, 2);
INSERT INTO `t_employee` VALUES (4, Vinylon, 1);
INSERT INTO `t_employee` VALUES (5, Dog, 2);


Employee.java

package com.fancy.po;

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.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "t_employee")
public class Employee {

    private Integer employeeId;
    private String  employeeName;
    private Company company;
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Integer getEmployeeId() {
        return employeeId;
    }
    /**
     * @ManyToOne:多对一,cascade:级联,请参考上一篇
      * fetch = FetchType.LAZY,延迟加载策略,如果不想延迟加载可以用FetchType.EAGER
     */
    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH},fetch = FetchType.LAZY)
    @JoinColumn(name = "cid")
    public Company getCompany() {
        return company;
    }
    public String getEmployeeName() {
        return employeeName;
    }
    public void setEmployeeId(Integer employeeId) {
        this.employeeId = employeeId;
    }
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
    public void setCompany(Company company) {
        this.company = company;
    }
}


Company.java

package com.fancy.po;

import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "t_company")
public class Company {

    private Integer companyId;
    private String  companyName;
    private Set<Employee> employees;
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Integer getCompanyId() {
        return companyId;
    }
    /**
     * @OneToMany 与 OneToOne相似的也用mappedBy,参考了Employee
     */
    @OneToMany(mappedBy = "company")
    public Set<Employee> getEmployees() {
        return employees;
    }
    public String getCompanyName() {
        return companyName;
    }
    public void setCompanyId(Integer companyId) {
        this.companyId = companyId;
    }
    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }
    public void setEmployees(Set<Employee> employees) {
        this.employees = employees;
    }
}


Test.java

package com.fancy.test;

import java.util.Iterator;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import com.fancy.po.Company;
import com.fancy.po.Employee;

public class Test {

    public static void main(String[] args) {
        //读取hibernate配置,默认读取classpath下的hibernate.cfg.xml
        Configuration conf = new AnnotationConfiguration();    
        //构建session工厂
         SessionFactory sessionFactory = conf.configure().buildSessionFactory();
        //打开session
        Session session = sessionFactory.openSession();
        //开始事务
         session.beginTransaction();
        // * * * * * * * * * * * * * * * * * * * * * * * * * * * *
        //test1(session);   //测试 1
        //test2(session);  //测试  2
        test3(session);   //测试   3
        // * * * * * * * * * * * * * * * * * * * * * * * * * * * *
        //提交事务
         session.getTransaction().commit();
        //关闭session工厂
         sessionFactory.close();
        //关闭session
        session.close();
    }
    public static void test1(Session session){
        Company company = (Company)session.get(Company.class, 1); //发出Company的select语句
         Set<Employee> employee = company.getEmployees();         //不发出Employee的select语句
         System.out.println("Company :" + company.getCompanyName());
        System.out.println("CountSum:" + employee.size()); //Employee初次被使用,发出select语句
         Iterator<Employee> it = employee.iterator(); //Employee不再发出select语句
         while(it.hasNext()){
          System.out.println("EmployeeName:" + it.next().getEmployeeName());
        }
    }
    public static void test2(Session session){
       Company company = (Company)session.get(Company.class, 2);//发出Company的select语句
        Set<Employee> employee = company.getEmployees();        //不发出Employee的select语句
        Iterator<Employee> it = employee.iterator(); //发出Employee的select语句
        Employee e = null;
       Boolean first = false;
       while(it.hasNext()){
          e = it.next();
          if(!first){
              System.out.println("EmployeeId:[" + e.getEmployeeId() + "] information will be change");
              e.setEmployeeName("fancy"); //更改雇员名字
            //  session.save(e);  //发出Employee的update语句,不发出Company的update语句
                session.save(company);    //发出Employee的update语句,不发出Company的update语句
                first = true;
            }
            System.out.println("EmployeeName:" + e.getEmployeeName());
        }
    }
    public static void test3(Session session){
        Employee employee = (Employee)session.get(Employee.class, 1);//发出Employee的select语句
         Company  company  = (Company)session.get(Company.class, 1);//发出Company的select语句
         company.setCompanyName("Oracle"); //更改公司名字
    //  session.save(company);//发出Company的update语句,不发出Employee的update语句
         session.save(employee);//发出Company的update语句,不发出Employee的update语句
    }
}


原文地址:hibernate one-to-many many-to-one 双向注解
参考:

hibernate annotation 之 注解声明

hibernate annotation 之 主键生成策略

hibernate annotation 之 一对一 单/双 向外键关联

hibernate annotation 之 一对多单向外键关联

hibernate annotation 之 多对一单向外键关联

hibernate annotation 之 一对多、多对一双向外键关联

hibernate one-to-many many-to-one 双向注解,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。