建表语句:

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 ('', 'Sun');
INSERT INTO `t_company` VALUES ('', '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 ('', 'Tom', '');
INSERT INTO `t_employee` VALUES ('', 'Summ', '');
INSERT INTO `t_employee` VALUES ('', 'Cat', '');
INSERT INTO `t_employee` VALUES ('', 'Vinylon', '');
INSERT INTO `t_employee` VALUES ('', 'Dog', '');

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 双向注解的更多相关文章

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

    注解(Annotation),也叫元数据.一种代码级别的说明.它是JDK1.5及以后版本引入的一个特性,与类.接口.枚举是在同一个层次.它可以声明在包.类.字段.方法.局部变量.方法参数等的前面,用来 ...

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

    注解(Annotation),也叫元数据.一种代码级别的说明.它是JDK1.5及以后版本引入的一个特性,与类.接口.枚举是在同一个层次.它可以声明在包.类.字段.方法.局部变量.方法参数等的前面,用来 ...

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

    上篇文章讨论了单向关联的一对多映射,在一的一端维护双向的关系这样的做法尽管能实现可是存在非常多缺陷,首先生成非常多多余的SQL语句,由于多的一端不维护关系,仅仅有一的一端维护,在进行操作时一的一端会发 ...

  4. hibernate 2 一对多、多对一 双向映射

    多对一或一对多中,在多的一方维护关系效率高 一:java实体类 1.Classes.java package cn.gs.ly.school.entity; import java.util.Set; ...

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

    下面是User类: @onetomany @Entity @Table(name="user") public class User implements Serializable ...

  6. Hibernate(12)_基于主键的双向1对1

    一.基于主键的双向1对1 1.介绍: 基于主键的映射策略:指一端的主键生成器使用 foreign 策略,表明根据"对方"的主键来生成自己的主键,自己并不能独立生成主键. <p ...

  7. Hibernate(11)_基于外键的双向1对1

    一.基于外键的双向1对1 对于基于外键的1-1关联,其外键可以存放在任意一边,在需要存放外键一端,增加many-to-one元素.为many-to-one元素增加unique="true&q ...

  8. Hibernate 注解(Annotations 二)一对一双向注解

    注解(Annotation),也叫元数据.一种代码级别的说明.它是JDK1.5及以后版本引入的一个特性,与类.接口.枚举是在同一个层次.它可以声明在包.类.字段.方法.局部变量.方法参数等的前面,用来 ...

  9. Hibernate入门(2)- 不用配置用注解

    在上一个例子里面,我用的配置文件的方式,这次改成注解. pom.xml 增加了hibernate-commons-annotations和hibernate-annotations <proje ...

随机推荐

  1. nginx http跳转到https

    server { listen 80; server_name www.888.com; location / { #index.html放在虚拟主机监听的根目录下 root /usr/local/n ...

  2. ORACLE 常用数值函数

    1 ABS(n)返回数值弄参数的绝对值.它接受一个数值型值作为输入参数,或者任何可以隐式地转换为数值型值的值.并且返回数值型值的绝对值. Select abs(-1) from dual ABS(-1 ...

  3. Myisam and InnoDB

    MyISAM引擎的特点: 1.堆组织表:2.不支持事务:3.数据文件和索引文件分开存储:4.支持全文索引:5.主键索引和二级索引完全一样都是B+树的数据结构,只有是否唯一的区别(主键和唯一索引有唯一属 ...

  4. DW(四):Azure域控服务器配置

    polybase集群要求使用相同的域账号,本节介绍选择用Azure虚拟机搭建自己的内网DNS服务器和域控 创建虚拟网络polybase,创建名为DNS的子网,如下图: 创建虚拟机,选择polybase ...

  5. jquery 设置select 默认值

    $('#@(Perfix)OrgType').children("option").each(function () { var temp_value = $(this).val( ...

  6. HTML 元素

    HTML 文档是由 HTML 元素定义的. HTML 元素 HTML 元素指的是从开始标签(start tag)到结束标签(end tag)的所有代码. 开始标签 元素内容 结束标签 <p> ...

  7. xmodem, ymodem & zmodem

    这三个是modem文件传输协议. https://en.wikipedia.org/wiki/XMODEM https://en.wikipedia.org/wiki/YMODEM https://e ...

  8. MySQL时间戳和时间格式转换函数

    MySQL时间戳和时间格式转换函数:unix_timestamp and from_unixtime unix_timestamp将时间转化成时间戳格式.from_unixtime将时间戳转化成时间格 ...

  9. bzoj4637: 期望

    Description 在米国有一所大学,名叫万国歌剧与信息大学(UniversalOperaandInformaticasUniversity).简称UOI大学.UO I大学的建筑与道路分布很有趣, ...

  10. 71. Simplify Path

    Given an absolute path for a file (Unix-style), simplify it. For example,path = "/home/", ...