环境:
Hibernate 3.3.1 Maven 3.0.4 MySQL 5.5.13 Myeclipse 8.6.1
建表语句:
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; /** * ----------------------------------------- * @文件: Employee.java * @作者: fancy * @邮箱: fancyzero@yeah.net * @时间: 2012-6-10 * @描述: 实体类 * ----------------------------------------- */ /** * 下面只说@ManyToOne,如需了解其他注解, * 可以参考上一篇:http://www.cnblogs.com/fancyzero/archive/2012/06/10/hibernate-one-to-one-annotation.html */ @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; /** * ----------------------------------------- * @文件: Company.java * @作者: fancy * @邮箱: fancyzero@yeah.net * @时间: 2012-6-10 * @描述: 实体类 * ----------------------------------------- */ /** * 下面只说@OneToMany,如需了解其他注解, * 可以参考上一篇:http://www.cnblogs.com/fancyzero/archive/2012/06/10/hibernate-one-to-one-annotation.html */ @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; } }
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.fancy</groupId> <artifactId>hibernate-annotation-many-to-one-example</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>hibernate-annotation-many-to-one-example</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- hibernate jar --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.3.1.ga</version> </dependency> <!-- hibernate annotation jar --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>3.3.1.GA</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.17</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> </project>
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; /** * ----------------------------------------- * @文件: Test.java * @作者: fancy * @邮箱: fancyzero@yeah.net * @时间: 2012-6-10 * @描述: 测试类 * ----------------------------------------- */ 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语句 } }