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 ('', '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 one-to-many many-to-one 双向注解的更多相关文章
- Hibernate 注解(Annotations 四)多对多双向注解
注解(Annotation),也叫元数据.一种代码级别的说明.它是JDK1.5及以后版本引入的一个特性,与类.接口.枚举是在同一个层次.它可以声明在包.类.字段.方法.局部变量.方法参数等的前面,用来 ...
- Hibernate 注解 (Annotations 三)多对一双向注解
注解(Annotation),也叫元数据.一种代码级别的说明.它是JDK1.5及以后版本引入的一个特性,与类.接口.枚举是在同一个层次.它可以声明在包.类.字段.方法.局部变量.方法参数等的前面,用来 ...
- 【Hibernate步步为营】--(一对多映射)之双向关联
上篇文章讨论了单向关联的一对多映射,在一的一端维护双向的关系这样的做法尽管能实现可是存在非常多缺陷,首先生成非常多多余的SQL语句,由于多的一端不维护关系,仅仅有一的一端维护,在进行操作时一的一端会发 ...
- hibernate 2 一对多、多对一 双向映射
多对一或一对多中,在多的一方维护关系效率高 一:java实体类 1.Classes.java package cn.gs.ly.school.entity; import java.util.Set; ...
- hibernate之实体@onetomany和@manytoone双向注解(转)
下面是User类: @onetomany @Entity @Table(name="user") public class User implements Serializable ...
- Hibernate(12)_基于主键的双向1对1
一.基于主键的双向1对1 1.介绍: 基于主键的映射策略:指一端的主键生成器使用 foreign 策略,表明根据"对方"的主键来生成自己的主键,自己并不能独立生成主键. <p ...
- Hibernate(11)_基于外键的双向1对1
一.基于外键的双向1对1 对于基于外键的1-1关联,其外键可以存放在任意一边,在需要存放外键一端,增加many-to-one元素.为many-to-one元素增加unique="true&q ...
- Hibernate 注解(Annotations 二)一对一双向注解
注解(Annotation),也叫元数据.一种代码级别的说明.它是JDK1.5及以后版本引入的一个特性,与类.接口.枚举是在同一个层次.它可以声明在包.类.字段.方法.局部变量.方法参数等的前面,用来 ...
- Hibernate入门(2)- 不用配置用注解
在上一个例子里面,我用的配置文件的方式,这次改成注解. pom.xml 增加了hibernate-commons-annotations和hibernate-annotations <proje ...
随机推荐
- CSS之background属性
css背景是个很有意思的东西,可设置 背景色:background-color 背景图:backgoround-image 背景图显示相对位置:background-position,正数图片往右下移 ...
- 必须Mark!43个优秀的Swift开源项目推荐
摘要:拥有着苹果先天生态优势的Swift自发布以来,各种优秀的开源项目便层出不穷.本文作者站在个人的角度,将2014年Swift开源项目做了一个甄别.筛选,从工具.存储.网络.界面.框架到Demo以及 ...
- SQL SERVER 只有MDF文件的恢复
方式一: .create a database same name as .mdf file; .Stop SQL Server; . recover .mdf file; . Start SQL S ...
- smarty模板基础
将前台后台隔离,前台控制显示,后台控制逻辑/内容,与cms类似 原理: 用户访问text.php页面,后台调用类smarty.class.php显示静态模板;
- Struts2 - 常用的constant总结
见注释 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC &quo ...
- 利用百度地图API,获取经纬度坐标
利用百度地图API,获取经纬度坐标 代码很简单,但在网上没找到现成的获取地图经纬度的页面. 就是想,给当前页面传递一个经纬度,自动定位到此经纬度.然后可以重新选择,选择完返回经纬度. 效果如下: 源代 ...
- WPF拖到、移动控件
只需2个事件和一个point变量即可: Point mouse_offset = , ); void TC_MouseLeftButtonDown(object sender, MouseButton ...
- Return 和 Break 的区别
前段日子发布的负面情绪太多了,哦哦,其实我需要的是努力,努力提高自己的真实能力.经历了好多的鄙视否定,我已经没有最初那么敏感,心态平和了许多.我没有借口说基础不好了,一年了,要努力的话,那么我应该不会 ...
- Perl调用外部命令的方式和区别
主要的方式简述如下:1. system("command");使用该命令将开启一个子进程执行引号中的命令,父进程将等待子进程结束并继续执行下面的代码. 2. exec(" ...
- Apache日志不记录图片文件设置方法和来源日志的配置
Apache日志不记录图片文件设置方法 <FilesMatch "\.(ico|gif|jpg|swf)">SetEnv IMAG 1</FilesMatch&g ...