本文共 3146 字,大约阅读时间需要 10 分钟。
2.joined-subclass映射策略
特点:父表的数据由父表保存,子表的数据由父表和子表共同保存。子类和父类共有的 属性保存在父表当中,子类扩展的属性保存在子表当中。采取该策略不需要辨别列。要为子表提供一个列【主键】映射父表的主键 表: create table g_product( --父表-- p_id integer primary key, p_name varchar2(30), p_price number(4,2) ) create table g_book( --子表-- c_id integer primary key references g_product(p_id),--与父表关联-- c_author varchar2(40) ) 映射文件 <joined-subclass name="Book" table="g_book" > <key column="c_id"></key><!-- 外键声明 --> <property name="author" column="c_author"></property> </joined-subclass>1.O提供对象属性实体类Product.java 和 Book.java
package com.jsu.hb.pojo;public class Product { private Integer id; private String name; private Double price; 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 Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } }
Book.java
package com.jsu.hb.pojo;public class Book extends Product { private String author; public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
2.R建表
create table g_product( p_id integer primary key, p_name varchar2(30), p_price number(6,2))create table g_book( c_id integer primary key references g_product(p_id), c_author varchar2(40))
3.提供映射文件joined.hbm.xml
4.在hibernate.cfg.xml文件中对映射文件进行注册
true true oracle.jdbc.OracleDriver jdbc:oracle:thin:@127.0.0.1:1521:oracle scott tiger org.hibernate.dialect.Oracle9iDialect
5.提供工具类HibernateUtil.java
package com.jsu.hb.util;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtil { private static SessionFactory sf; private static ThreadLocaltl= new ThreadLocal (); static{ try{ Configuration cfg = new Configuration(); cfg.configure(); sf=cfg.buildSessionFactory(); }catch(Exception e){ e.printStackTrace(); } } public static Session openSession(){ return sf.openSession(); } public static Session getCurrentSession(){ Session session = tl.get();//先从储存的线程中查找 if(session==null){ session=openSession(); tl.set(session); return session; } return session; }}
6.提供测试类TestJoined.java
package com.jsu.hb.test;import org.hibernate.Session;import org.hibernate.Transaction;import org.junit.Test;import com.jsu.hb.pojo.Book;import com.jsu.hb.pojo.Product;import com.jsu.hb.util.HibernateUtil;public class TestJoined { @Test public void save(){ Product p = new Product(); p.setName("小米"); p.setPrice(1999.0); Book b = new Book(); b.setName("围城"); b.setPrice(38.5); b.setAuthor("沈从文"); Session session = HibernateUtil.getCurrentSession(); Transaction tx = session.getTransaction(); tx.begin(); session.save(p);//保存产品 //session.save(b);//保存图书 tx.commit(); }}
转载地址:http://ephhi.baihongyu.com/