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、創(chuàng)建產品 3、將產品添加到類別,將類別設置到產品 4、執(zhí)行保存 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, 執(zhí)行的是update,不執(zhí)行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 創(chuàng)建用于操作數據庫的Session工廠 // SessionFactory 負責保存和使用所有配置,消耗內存資源非常大 // 線程安全 // 保證在web項目中,只創(chuàng)建一個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; } }

浙公網安備 33010602011771號