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 双向注解

时间: 2024-10-04 03:26:28

hibernate one-to-many many-to-one 双向注解的相关文章

Hibernate 注解(Annotations 四)多对多双向注解

注解(Annotation),也叫元数据.一种代码级别的说明.它是JDK1.5及以后版本引入的一个特性,与类.接口.枚举是在同一个层次.它可以声明在包.类.字段.方法.局部变量.方法参数等的前面,用来对这些元素进行说明,注释. 接下来讲解多对多双向注解: 我以用户和房子作为示例讲解. 第一步:准备实体类 House(房间表) package cn.manytomany.entity; import javax.persistence.*; import java.util.HashSet; im

Hibernate 注解 (Annotations 三)多对一双向注解

注解(Annotation),也叫元数据.一种代码级别的说明.它是JDK1.5及以后版本引入的一个特性,与类.接口.枚举是在同一个层次.它可以声明在包.类.字段.方法.局部变量.方法参数等的前面,用来对这些元素进行说明,注释. 接下来我们讲解一下多对一双向注解: 我以部门表和员工表作为示例讲解. 第一步:创建实体类 Dept(部门表) package cn.onetomanydouble.entity; import org.hibernate.annotations.*; import org

【Hibernate步步为营】--(一对多映射)之双向关联

上篇文章讨论了单向关联的一对多映射,在一的一端维护双向的关系这样的做法尽管能实现可是存在非常多缺陷,首先生成非常多多余的SQL语句,由于多的一端不维护关系,仅仅有一的一端维护,在进行操作时一的一端会发出多余的update语句:其次,由于多的一端不知道一的一端存在,所以在保存多的一端时假设外键为null值,而且在设计数据库时关系字段设为非空,则将无法保存数据.由于单向关联一对多存在非常多缺点那就没有其他的办法了吗,能够採用双向关联来优化. 一.一对多双向关联 这里继续採用上篇文章的学生和班级作为演

hibernate之实体@onetomany和@manytoone双向注解(转)

下面是User类: @onetomany @Entity @Table(name="user") public class User implements Serializable{ private static final long serialVersionUID = 6177417450707400228L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="id") priva

Hibernate 一对一、一对多、多对多注解属性的总结

mappedBy: 所填内容必为本类在另一方的字段名. 表示:本类放弃控制关联关系,所有对关联关系的控制,如:建立.解除与另一方的关系,都由对方控制,本类不管.举个例子: Teacher和Student之间是多对多关联关系,在Student端的teachers字段的@ManyToMany注解里面,配置属性mappedBy = "students".表示:学生没有资格控制与老师的关联关系(如:建立关系.删除关系),只有老师才有资格控制关联关系.学生不能说:"我们两做朋友吧&qu

Hibernate or JPA Annotation中BLOB、CLOB注解写法

BLOB和CLOB都是大字段类型,BLOB是按二进制字节码来存储的.而CLOB是能够直接存储字符串的. 在hibernate or JPA Annotation中.实体BLOB.CLOB类型的注解与普通的实体属性有些不同,详细操作例如以下: BLOB类型,类型声明为byte[]: private byte[] content; 注解: @Lob @Basic(fetch = FetchType.LAZY) @Column(name = "CONTENT", columnDefiniti

Hibernate 一对一、一对多、多对多注解cascade属性的总结

作用:是否级联被注解字段里面的对象.可选值:javax.persistence.CascadeType.PERSIST, MERGE, REMOVE, REFRESH, DETACH, ALL.可选其中的一个或多个,选一个时,花括号可用可不用. PERSIST 级联session的persist操作.假设Student类和teachers字段的@ManyToMany注解上配置有cascade = {CascadeType.PERSIST},那么,当stu1对象set了一个teachers集合(这

Hibernate 多对多 中间表含有其他字段 注解方式实现

需求: 两个实体类:Teacher.class Student.class 中间表包含了一个额外字段:score Teacher.calss id name 1 Mr.zhang 2 Mr.wang Student.class id name 1 Xiaoming 2 Xiaohong 中间表 id teacher_id student_id score 1 1 1 89 2 1 2 90 解决办法: 按照传统的多对多注解实现,中间表是以自身id为默认主键,另外包含了两个实体类的id,共3个字段

Hibernate在实体类中对于时间的注解

在时间类型DATE 属性上添加一个 @Temporal(TemporalType.DATE)(精确到年月日)@Temporal(TemporalType.TIME)(精确到时分秒)@Temporal(TemporalType.TIMESTAMP)(默认年月日时分秒)示例: @Temporal(TemporalType.DATE)private Date updateDate; 有了这个就不需要用java代码将时间戳,转换成需要的日期格式.直接在实体类中进行注解!