hibernate级联操作
程序员文章站
2022-05-02 08:17:34
...
准备条件:
1. 创建hibernate3工程
2. 导入hibernate的jar包
3. 创建数据库hibernate3,及表customers,orders
一. 一对多双向关联
1. hibernate.cfg.xml
2. Customer.java
3. Order.java
4. Customer.hbm.xml
5. Order.hbm.xml
6. Test.java
二. 一对多双向自身关联
1. hibernate.cfg.xml
2. Category.java
3. Category.hbm.xml
4. Test.java
三. 一对一关联
第一种方式:
1. Hibernate.cfg.xml
2. Student.java
3. Certificate.java
4. Student.hbm.xml
5. Certificate.hbm.xml
6. BM.java
7. StudentDAO.java
8. HibernateUtil.java
第二种方式:
与第一种方式基本相同,唯一不同的是以下文件:
1. Certificate.hbm.xml
四. 多对多关联
1. Hibernate.cfg.xml
2. Student.java
3. Course.java
4. Student.hbm.xml
5. Course.hbm.xml
6. BM.java
7. StudentDAO.java
8. HibernateUtil.java
1. 创建hibernate3工程
2. 导入hibernate的jar包
3. 创建数据库hibernate3,及表customers,orders
一. 一对多双向关联
1. hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<!--
<property name="format_sql">true</property>
-->
<property name="show_sql">true</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate3</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="customer.hbm.xml" />
<mapping resource="order.hbm.xml" />
</session-factory>
</hibernate-configuration>
2. Customer.java
package com.hibernate3.bean;
import java.util.Set;
public class Customer {
private Long id;
private String name;
private Set orders;
public Customer(){
}
public Customer(String name,Set orders){
this.name=name;
this.orders=orders;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set getOrders() {
return orders;
}
public void setOrders(Set orders) {
this.orders = orders;
}
}
3. Order.java
package com.hibernate3.bean;
public class Order {
private Long id;
private String orderNumber;
private Customer customer;
public Order(){
}
public Order(String orderNumber,Customer customer){
this.orderNumber=orderNumber;
this.customer=customer;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getOrderNumber() {
return orderNumber;
}
public void setOrderNumber(String orderNumber) {
this.orderNumber = orderNumber;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
4. Customer.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping >
<class name="com.hibernate3.bean.Customer" table="customers">
<id name="id" column="id" type="long">
<generator class="increment"></generator>
</id>
<property name="name" column="name" type="string"></property>
<set name="orders" cascade="all" inverse="true" fetch="join" >
<key column="customer_id"></key>
<one-to-many class="com.hibernate3.bean.Order"/>
</set>
</class>
</hibernate-mapping>
5. Order.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.hibernate3.bean.Order" table="orders">
<id name="id" column="id" type="long">
<generator class="increment"></generator>
</id>
<property name="orderNumber" type="string" >
<column name="order_number" length="15"></column>
</property>
<many-to-one name="customer" column="customer_id" class="com.hibernate3.bean.Customer"></many-to-one>
</class>
</hibernate-mapping>
6. Test.java
package com.hibernate3.bean;
import java.util.HashSet;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Test {
private static SessionFactory sessionFactory;
static{
try{
sessionFactory=new Configuration().configure().buildSessionFactory();
}catch (Exception e) {
System.out.println("获得sessionFactory出错");
e.printStackTrace();
}
}
public static void saveCustomerAndOrderWithCascade(){
Session session=sessionFactory.openSession();
Transaction tx=null;
try{
tx=session.beginTransaction();
Customer customer=new Customer("zs",new HashSet());
Order o1=new Order("no1",customer);
Order o2=new Order("no2",customer);
customer.getOrders().add(o1);
customer.getOrders().add(o2);
session.save(customer);
tx.commit();
}catch(Exception ex){
System.out.println("保存数据时出错");
ex.printStackTrace();
if(tx!=null){
tx.rollback();
}
}finally{
session.close();
}
}
public static void main(String[] args)
{
saveCustomerAndOrderWithCascade();
}
}
二. 一对多双向自身关联
1. hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<!--
<property name="format_sql">true</property>
-->
<property name="show_sql">true</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate3</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="Category.hbm.xml"/>
</session-factory>
</hibernate-configuration>
2. Category.java
package com.hibernate3.bean;
import java.util.Set;
public class Category {
private Long id;
private String name;
private Category parentCategory;
private Set childCategorys;
public Category(){
}
public Category(String name,Category parentCategory,Set childCategorys){
this.name=name;
this.parentCategory=parentCategory;
this.childCategorys=childCategorys;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Category getParentCategory() {
return parentCategory;
}
public void setParentCategory(Category parentCategory) {
this.parentCategory = parentCategory;
}
public Set getChildCategorys() {
return childCategorys;
}
public void setChildCategorys(Set childCategorys) {
this.childCategorys = childCategorys;
}
}
3. Category.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping >
<class name="com.hibernate3.bean.Category" table="categories">
<id name="id" column="id" type="long">
<generator class="increment"></generator>
</id>
<property name="name" column="name" type="string"></property>
<set name="childCategorys" cascade="all" inverse="true" >
<key column="category_id"></key>
<one-to-many class="com.hibernate3.bean.Category"/>
</set>
<many-to-one name="parentCategory" column="category_id" class="com.hibernate3.bean.Category"></many-to-one>
</class>
</hibernate-mapping>
4. Test.java
fpackage com.hibernate3.bean;
import java.util.HashSet;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Test {
private static SessionFactory sessionFactory;
static{
try{
sessionFactory=new Configuration().configure().buildSessionFactory();
}catch (Exception e) {
System.out.println("获得sessionFactory出错");
e.printStackTrace();
}
}
public static void saveCategoryWithCascade(){
Session session=sessionFactory.openSession();
Transaction tx=null;
try{
tx=session.beginTransaction();
//食口类别
Category footCategory=new Category("foot",null,new HashSet());
//水果类别
Category fruitCategory=new Category("fruit",null,new HashSet());
//蔬菜类别
Category vegetableCategory=new Category("vegetable",null,new HashSet());
//苹果类别
Category appleCategory=new Category("apple",null,new HashSet());
//桔子类别
Category orangeCategory=new Category("orange",null,new HashSet());
//西红柿类别
Category tomatoCategory=new Category("tomato",null,new HashSet());
footCategory.getChildCategorys().add(fruitCategory);
fruitCategory.setParentCategory(footCategory);
footCategory.getChildCategorys().add(vegetableCategory);
vegetableCategory.setParentCategory(footCategory);
fruitCategory.getChildCategorys().add(appleCategory);
appleCategory.setParentCategory(fruitCategory);
fruitCategory.getChildCategorys().add(orangeCategory);
orangeCategory.setParentCategory(fruitCategory);
vegetableCategory.getChildCategorys().add(tomatoCategory);
tomatoCategory.setParentCategory(vegetableCategory);
session.save(footCategory);
tx.commit();
}catch(Exception ex){
System.out.println("保存数据时出错");
ex.printStackTrace();
if(tx!=null){
tx.rollback();
}
}finally{
session.close();
}
}
public static void main(String[] args)
{
saveCategoryWithCascade();
}
}
三. 一对一关联
第一种方式:
1. Hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<!--
<property name="format_sql">true</property>
-->
<property name="show_sql">true</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate3</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="Certificate.hbm.xml" />
<mapping resource="Student.hbm.xml" />
</session-factory>
</hibernate-configuration>
2. Student.java
package com.hibernate3.bean;
public class Student {
private String id; //标识ID
private String cardId; //学号
private String name; //姓名
private int age; //年龄
private Certificate cer; //身份证
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Certificate getCer() {
return cer;
}
public void setCer(Certificate cer) {
this.cer = cer;
}
}
3. Certificate.java
package com.hibernate3.bean;
public class Certificate {
private String id;
private String describe;
private Student stu;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescribe() {
return describe;
}
public void setDescribe(String describe) {
this.describe = describe;
}
public Student getStu() {
return stu;
}
public void setStu(Student stu) {
this.stu = stu;
}
}
4. Student.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.hibernate3.bean.Student" table="students">
<id name="id" column="id" type="string" unsaved-value="null">
<generator class="uuid"></generator>
</id>
<property name="name" column="name" type="string"></property>
<property name="cardId" column="card_id" type="string"></property>
<property name="age" column="age" type="integer"></property>
<one-to-one name="cer" class="com.hibernate3.bean.Certificate" cascade="all" ></one-to-one>
</class>
</hibernate-mapping>
5. Certificate.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.hibernate3.bean.Certificate" table="certificates">
<id name="id" column="id" type="string">
<generator class="foreign">
<param name="property">stu</param>
</generator>
</id>
<property name="describe" column="`describe`" type="string"></property>
<one-to-one name="stu" class="com.hibernate3.bean.Student" constrained="true"
cascade="none"></one-to-one>
</class>
</hibernate-mapping>
6. BM.java
package com.hibernate3.bean;
public class BM {
public static void main(String[] args) {
Student stu=new Student();
stu.setName("zs");
stu.setCardId("123456");
stu.setAge(33);
Certificate cer=new Certificate();
cer.setDescribe("park");
stu.setCer(cer);
cer.setStu(stu);
StudentDAO.saveObj(stu);
}
}
7. StudentDAO.java
package com.hibernate3.bean;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class StudentDAO {
static Session session=null;
static Transaction tx=null;
public static void saveObj(Object o){
try{
session=HibernateUtil.getSession();
tx=session.beginTransaction();
session.save(o);
tx.commit();
}catch(Exception ex){
if(tx!=null){
tx.rollback();
}
ex.printStackTrace();
}finally{
HibernateUtil.closeSession(session);
}
}
}
8. HibernateUtil.java
package com.hibernate3.bean;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionFactory;
static{
try{
sessionFactory=new Configuration().configure().buildSessionFactory();
}catch(Exception ex){
System.out.println("获得sessionFactory时出错");
ex.printStackTrace();
}
}
public static void closeSession(Session session){
if(session!=null){
session.close();
}
}
public static Session getSession(){
Session session=sessionFactory.openSession();
return session;
}
}
第二种方式:
与第一种方式基本相同,唯一不同的是以下文件:
1. Certificate.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.hibernate2.bean.Certificate" table="certificates">
<id name="id" column="id" type="string">
<generator class="uuid"></generator>
</id>
<property name="describe" column="`describe`" type="string"></property>
<many-to-one name="stu" column="stu_id" class="com.hibernate2.bean.Student" unique="true"></many-to-one>
</class>
</hibernate-mapping>
四. 多对多关联
1. Hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<!--
<property name="format_sql">true</property>
-->
<property name="show_sql">true</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate3</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="Student.hbm.xml" />
<mapping resource="Course.hbm.xml" />
</session-factory>
</hibernate-configuration>
2. Student.java
package com.hibernate3.bean;
import java.util.Set;
public class Student {
private String id;
private String cardId;
private String name;
private int age;
private Set courses;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Set getCourses() {
return courses;
}
public void setCourses(Set courses) {
this.courses = courses;
}
}
3. Course.java
package com.hibernate3.bean;
import java.util.Set;
public class Course {
private String id;
private String name;
private Set students;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set getStudents() {
return students;
}
public void setStudents(Set students) {
this.students = students;
}
}
4. Student.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping >
<class name="com.hibernate3.bean.Student" table="students">
<id name="id" column="id" type="string" unsaved-value="null">
<generator class="uuid"></generator>
</id>
<property name="cardId" column="card_id" type="string"></property>
<property name="name" column="name" type="string"></property>
<property name="age" column="age" type="integer"></property>
<set name="courses" cascade="none" inverse="true" table="student_course" >
<key column="stu_id"></key>
<many-to-many class="com.hibernate3.bean.Course" column="course_id"></many-to-many>
</set>
</class>
</hibernate-mapping>
5. Course.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping >
<class name="com.hibernate3.bean.Course" table="course">
<id name="id" column="id" type="string" unsaved-value="null">
<generator class="uuid"></generator>
</id>
<property name="name" column="name" type="string"></property>
<set name="students" cascade="save-update" table="student_course" >
<key column="course_id"></key>
<many-to-many class="com.hibernate3.bean.Student" column="stu_id"></many-to-many>
</set>
</class>
</hibernate-mapping>
6. BM.java
package com.hibernate3.bean;
public class BM {
/**
* @param args
*/
public static void main(String[] args) {
StudentDAO.mdfChoice();
}
}
7. StudentDAO.java
package com.hibernate3.bean;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class StudentDAO {
public static void mdfChoice(){
Session session=null;
Transaction tx=null;
try{
session=HibernateUtil.getSession();
tx=session.beginTransaction();
Student stu=(Student)session.createQuery(
"from Student as s where s.name='zs'").uniqueResult();
Course cer=(Course)session.createQuery(
"from Course as c where c.name='english'").uniqueResult();
stu.getCourses().add(cer);
cer.getStudents().add(stu);
tx.commit();
}catch(Exception ex){
if(tx!=null){
tx.rollback();
}
ex.printStackTrace();
}finally{
HibernateUtil.closeSession(session);
}
}
}
8. HibernateUtil.java
package com.hibernate3.bean;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionFactory;
static{
try{
sessionFactory=new Configuration().configure().buildSessionFactory();
}catch(Exception ex){
System.out.println("获得sessionFactory时出错");
ex.printStackTrace();
}
}
public static void closeSession(Session session){
if(session!=null){
session.close();
}
}
public static Session getSession(){
Session session=sessionFactory.openSession();
return session;
}
}
上一篇: 判断质数,是输出yes,不是输出no
下一篇: spring读取properties