Hibernate 一对多关系操作
这里使用类别Category和产品Product举例。
Category与Product属于1:m 的关系,数据库如下:
那么,实体设计如下:
package com.sasa.domain; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; public class Category { public Category() {} private Integer id; private String c_name; private String descr; private Date create_tm; private Set<Product> Products = new HashSet<Product>(); public Set<Product> getProducts() { return Products; } public void setProducts(Set<Product> products) { Products = products; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getC_name() { return c_name; } public void setC_name(String c_name) { this.c_name = c_name; } public String getDescr() { return descr; } public void setDescr(String descr) { this.descr = descr; } public Date getCreate_tm() { return create_tm; } public void setCreate_tm(Date create_tm) { this.create_tm = create_tm; } @Override public String toString() { return "Category [id=" + id + ", c_name=" + c_name + ", descr=" + descr + ", create_tm=" + create_tm + ", Products=" + Products + "]"; } }
package com.sasa.domain; import java.time.LocalDateTime; public class Product { public Product() {} private Integer pid; private String pname; private Double price; private LocalDateTime create_tm; private Category category; public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public LocalDateTime getCreate_tm() { return create_tm; } public void setCreate_tm(LocalDateTime create_tm) { this.create_tm = create_tm; } @Override public String toString() { return "Product [pid=" + pid + ", pname=" + pname + ", price=" + price + ", create_tm=" + create_tm + ", category=" + category + "]"; } }
配置文件:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.sasa.domain"> <class name="Category" table="category"> <id name="id" column="id"> <generator class="native"></generator> </id> <property name="c_name"></property> <property name="descr"></property> <property name="create_tm"></property> <set name="products"> <key column="category_id"></key> <one-to-many class="Product"/> </set> </class> </hibernate-mapping>
name:引用属性名
column:外键名称
class:与此类相关的类的完整类名
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.sasa.domain"> <class name="Product" table="product"> <id name="pid" column="pid"> <generator class="native"></generator> </id> <property name="pname"></property> <property name="price"></property> <property name="create_tm"></property> <many-to-one name="category" column="category_id" class="Category"></many-to-one> </class> </hibernate-mapping>
当设计好之后,就可以书写代码测试了:
package com.sasa.service; import java.time.LocalDateTime; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.Test; import com.sasa.domain.Category; import com.sasa.domain.Product; import com.sasa.utils.HibernateUtils; public class CategoryService { @Test //新增类别和产品 public void addCategorys(){ Session session = HibernateUtils.getCurrentSession(); Transaction tran = session.beginTransaction(); //======================================== Category category = new Category(); category.setC_name("运动器材"); category.setDescr("sport"); Product p1 = new Product(); p1.setPname("足球"); p1.setPrice(100.00); Product p2 = new Product(); p2.setPname("篮球"); p2.setPrice(90.00); //一对多 category.getProducts().add(p1); category.getProducts().add(p2); //多对一 p1.setCategory(category); p2.setCategory(category); session.save(category); session.save(p1); session.save(p2); //========================================== tran.commit(); session.close(); } //为类别增加产品 public void addProductByCategory() { Session session = HibernateUtils.getCurrentSession(); Transaction tran = session.beginTransaction(); //==================================== //1、获得要操作的类别 2、创建产品 3、将产品添加到类别,将类别设置到产品 4、执行保存 Category category = session.get(Category.class, 9); Product product = new Product(); product.setPname("羽毛球"); product.setCreate_tm(LocalDateTime.now()); product.setPrice(40.50); category.getProducts().add(product); product.setCategory(category); session.save(product); //==================================== tran.commit(); session.close(); } //删除产品 public void delProductByCategory() { Session session = HibernateUtils.getCurrentSession(); Transaction tran = session.beginTransaction(); //==================================== //1、获得要操作的类别 2、获得要移除的产品 3、将产品从类别集合中移除 Category category = session.get(Category.class, 9); Product product = session.get(Product.class, 35); category.getProducts().remove(product); product.setCategory(null);//注意:数据库外键需设计为可空 这里的删除是将外键设置为null, 执行的是update,不执行delete //==================================== // tran.commit(); session.close(); } }
HibernateUtils.java:
package com.sasa.utils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtils { private static SessionFactory sessionFac; static { // Configuration 配置加载类,加载主配置,orm元数据加载 Configuration conf = new Configuration().configure(); // SessionFactory 创建用于操作数据库的Session工厂 // SessionFactory 负责保存和使用所有配置,消耗内存资源非常大 // 线程安全 // 保证在web项目中,只创建一个SessionFactory sessionFac = conf.buildSessionFactory(); } //获得Session //打开一个全新的Session public static Session openSession() { Session session = sessionFac.openSession(); return session; } //获得线程上绑定的Session public static Session getCurrentSession() { Session session = sessionFac.getCurrentSession(); return session; } }