1.在之前学习了单表的crud操作。在实际应用中,大都是多表关联操作,这篇会学习如何处理多表之间的关系。
2.考察书籍表和书籍分类表的关系。书籍表和书籍分类表之间是多对一的关系。数据库的表设计为:
3.在java中,如何使用类的关系来表明表与表之间关系
Book.java
public class Book implements Serializable{ private int id; private String name; private String author; private double price; private Date pubDate; private Category category;//在多的一端对一的一端的引用 //也就是说在多的一端可以获取到一的一端信息 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Date getPubDate() { return pubDate; } public void setPubDate(Date pubDate) { this.pubDate = pubDate; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; }}
Category.java
public class Category implements Serializable{ private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }}
4.映射文件关系
Book.hbm.xml
Category.hbm.xml
5.测试
public class HibernateTest { /** * 生成数据库表的工具方法 * */ @Test public void testCreateDB(){ Configuration cfg = new Configuration().configure(); SchemaExport se = new SchemaExport(cfg); //第一个参数 是否打印sql脚本 //第二个参数 是否将脚本导出到数据库中执行 se.create(true, true); } /** * 初始化表数据 */ @Test public void testInit(){ Session session = null; Transaction tx = null; try { session = HibernateUtil.getSession(); tx = session.beginTransaction(); Category c1 = new Category("计算机类"); Category c2 = new Category("文学"); Category c3 = new Category("历史"); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Book b1 = new Book("java","sun",30,df.parse("1995-05-23")); b1.setCategory(c1); Book b2 = new Book("struts","apache",40,df.parse("2006-09-12")); b2.setCategory(c1); Book b3 = new Book("明朝那些事儿","当年明月",70,df.parse("2008-05-23")); b3.setCategory(c3); Book b4 = new Book("水浒传","老撕",20,df.parse("1985-05-23")); b4.setCategory(c2); session.save(c1); session.save(c2); session.save(c3); session.save(b1); session.save(b2); session.save(b3); session.save(b4); tx.commit(); } catch (Exception e) { if(tx!=null) tx.rollback(); }finally { HibernateUtil.close(); } } /** * 在查询多的一端数据时可以获取一的一端的数据 */ @Test public void testGetData(){ Session session = HibernateUtil.getSession(); Book book = (Book)session.get(Book.class, 3); System.out.println(book.getId()+"--"+book.getName()+"---"+book.getAuthor()+ "---"+book.getPrice()+"---"+book.getPubDate()+"---"+book.getCategory().getName()); HibernateUtil.close(); }}
注意:初始化数据时,保存顺序,先保存的分类,再保存的书籍