Hibernate一对多级联操作

来源:互联网 发布:linux查看文件数量 编辑:程序博客网 时间:2024/05/21 08:42

使用hibernate对mysql进行一对多的级联增删查改操作:

一方为产品的分类(Category.java),多方为具体的产品(Product.java)


JavaBean(一方):

package com.yi.entity;import java.util.HashSet;import java.util.Set;/* * 一方 */public class Category {private Integer id;private String name;//关联产品private Set<Product> products = new HashSet<Product>();public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Set<Product> getProducts() {return products;}public void setProducts(Set<Product> products) {this.products = products;}}


javabean(多方):

package com.yi.entity;/* * 多方 */public class Product {private Integer id;private String name;//关联产品类型private Category category = new Category();public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Category getCategory() {return category;}public void setCategory(Category category) {this.category = category;}}


一方配置文件(Category.hbm.xml):

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping><!-- Class映射类 --><class name="com.yi.entity.Category" table="t_category"><!-- 主键映射(重要) --><id name="id"><!-- 策略 Native为id自增长 --><generator class="native"></generator></id><!-- 普通属性 --><property name="name"></property><!-- 一方配置,映射外键 --><!-- cascade: 级联操作。 一方的操作,同时也影响另一个方同样的操作save-update:  级联保存和更新delete: 级联删除all: save-update+delete: 级联保存,更新,删除Inverse: 关系的维护问题true: 放弃关系的维护(在一对多时最好放弃一方的,应为一方维护一次就要为多方产生和数据相同都的sql update语句,影响性能)false:  不放弃关系的维护 (默认值) --><set name="products" inverse="true" cascade="all"><key column="category_id"></key><!-- 关联的外键 --><one-to-many class="com.yi.entity.Product"/></set></class></hibernate-mapping>


多方配置文件(Product.hbm.xml):

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping><!-- Class映射类 --><class name="com.yi.entity.Product" table="t_product"><!-- 主键映射(重要) --><id name="id"><!-- 策略 Native为id自增长 --><generator class="native"></generator></id><!-- 普通属性 --><property name="name"></property><!-- 多方配置,映射外键 --><!-- cascade: 级联操作。 一方的操作,同时也影响另一个方同样的操作save-update:  级联保存和更新delete: 级联删除all: save-update+delete: 级联保存,更新,删除注意:这里的级联关系不能为all,否则在在删除多方的任何一个数据时,导致所在的外键关联的多方和一方全部删除--><many-to-one name="category"class="com.yi.entity.Category"column="category_id"cascade="save-update"></many-to-one></class></hibernate-mapping>


hibernate配置文件(hibernate.cfg.xml):

<?xml version="1.0"?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><!-- 连接数据库参数 --><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property><property name="hibernate.connection.url">jdbc:mysql:///hibernate?useUnicode=true&characterEncoding=utf-8</property><property name="hibernate.connection.username">root</property><property name="hibernate.connection.password">root</property><!-- 扩展参数 --><!-- 显示生成的SQL语句--><property name="hibernate.show_sql">true</property><!-- 格式化SQL语句 --><property name="hibernate.format_sql">true</property><!-- 如果表不存在将自动新建表,表名为配置文件中table对应的表名 --><property name="hibernate.hbm2ddl.auto">update</property><!-- 数据库方言(使用数据库的那种sql语句) --><property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property><!-- 一对多映射 --><mapping resource="com/yi/entity/Category.hbm.xml" /><mapping resource="com/yi/entity/Product.hbm.xml" /></session-factory></hibernate-configuration>


Utils工具类(HibernateUtils.java)

package com.yi.utils;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;/* * hibernate框架工具类 */public class HibernateUtils {private static Configuration config;private static SessionFactory sf;//通过静态加载动态代码块static{//加载hibernate.cfg.xml文件config = new Configuration();config.configure();//加载hibernate.cfg.xml文件sf = config.buildSessionFactory();}//返回Session对象public static Session getSession(){//返回sessionreturn sf.openSession();}}



Java测试文件(OneToMany.java):

package com.yi.test;import java.util.Iterator;import java.util.List;import java.util.Set;import org.hibernate.Query;import org.hibernate.Session;import org.junit.Test;import com.yi.entity.Category;import com.yi.entity.Product;import com.yi.utils.HibernateUtils;/* * 一对多关系映射测试 */public class OneToMany {//保存数据@Testpublic void Test1(){Session session = HibernateUtils.getSession();session.beginTransaction();Category categ = new Category();categ.setName("食品");Product p1 = new Product();p1.setName("巧克力");Product p2 = new Product();p2.setName("雪梨");//建立双向关系categ.getProducts().add(p1);categ.getProducts().add(p2);p1.setCategory(categ);p2.setCategory(categ);//保存数据session.save(categ);session.beginTransaction().commit();session.close();}//更新数据@Testpublic void Test2(){Session session = HibernateUtils.getSession();session.beginTransaction();//获取一方和多方的数据Category categ = session.get(Category.class,1);Product p = session.get(Product.class, 2);p.setName("魅族");//建立双向关系categ.getProducts().add(p);p.setCategory(categ);//更新数据session.update(categ);session.beginTransaction().commit();session.close();}//删除数据@Testpublic void Test3(){Session session = HibernateUtils.getSession();session.beginTransaction();////删除多表中的其中一个数据//Product p = session.get(Product.class, 11);//session.delete(p);//获取一方数据(删除一方和多方相同外键的所有数据一起删除)Category categ = session.get(Category.class,5);session.delete(categ);session.beginTransaction().commit();session.close();}//查询全部数据@Testpublic void Test4(){Session session = HibernateUtils.getSession();session.beginTransaction();Query query = session.createQuery("from Category");List list = query.list();Iterator it = list.iterator();while (it.hasNext()) {Category c = (Category)it.next();System.out.println("产品分类:" + c.getName());Set<Product> products = c.getProducts();for (Product product : products) {System.out.println("产品名称:" + product.getName());}}session.beginTransaction().commit();session.close();}//查询指定数据@Testpublic void Test5(){Session session = HibernateUtils.getSession();session.beginTransaction();//按名称查询Query query = session.createQuery("from Category c where c.name='手机'");List list = query.list();Iterator it = list.iterator();while (it.hasNext()) {Category c = (Category)it.next();System.out.println("产品分类:" + c.getName());Set<Product> products = c.getProducts();for (Product product : products) {System.out.println("产品名称:" + product.getName());}}session.beginTransaction().commit();session.close();}}


0 0
原创粉丝点击