Hibernate(七)多表联查之单向一对多

来源:互联网 发布:9.9元天天特价淘宝 编辑:程序博客网 时间:2024/05/22 19:19

单向之一对多

举例:枪和子弹,一把枪有许多子弹

1、工具类:HibernateUtil

public class HibernateUtilEX {    private static Configuration configuration = null;    private static SessionFactory sessionFactory = null;    // 本地化线程、    private static ThreadLocal<Session> localSession = null;    static {        try {            // 加载Hibernate配置文件(默认加载bihernate.cfg.xml)            configuration = new Configuration().configure();            // 获取SessionFactory工厂对象            sessionFactory = configuration.buildSessionFactory();            localSession = new ThreadLocal<Session>();        } catch (Exception e) {            System.out.println("加载hibernate映射文件失败");            e.printStackTrace();        }    }    /**     * 得到Session对象     *      * @return Session     */    public static Session openSession() throws HibernateException {        // 底层有一个Map<k,V>,K:线程ID,V:session ,一个线程绑定一个session        Session session = localSession.get();        if (session == null) {            session = sessionFactory.openSession();            localSession.set(session);        }        return session;    }    /**     * 关闭Session     *      * @throws HibernateException     */    public static void closeSession() throws HibernateException {        Session session = localSession.get();        if (session != null) {            session.close();        }        localSession.set(null);    }}

2、手枪实体类:GunEntity

public class GunEntity {    private int id;    private String type;    private Set<BulletEntity> bullets;  //子弹集合引用;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getType() {        return type;    }    public void setType(String type) {        this.type = type;    }    public Set<BulletEntity> getBullets() {        return bullets;    }    public void setBullets(Set<BulletEntity> bullets) {        this.bullets = bullets;    }    @Override    public String toString() {        return "GunEntity [id=" + id + ", type=" + type + ", bullets=" + bullets + "]";    }           }

配置文件:GunEntity.hbm.xml

<?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.zh.entity">    <class name="GunEntity" table="t_gun">        <!-- 映射标识属性(属性) -->        <id name="id" column="id" type="int">            <!-- 主键生成策略(自增主键) -->            <generator class="native" />        </id>        <!-- 映射普通属性 -->        <property name="type" column="type"></property>        <!-- 单向一对多 -->        <set name="bullets">            <!-- 指定外键 -->            <key column="gun_id"></key>            <!-- 映射关联类 -->            <one-to-many class="BulletEntity" />        </set>    </class></hibernate-mapping>

子弹实体类:BulletEntity

public class BulletEntity {    private int id;    private double caliber; //口径    private double weight;  //重量    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public double getCaliber() {        return caliber;    }    public void setCaliber(double caliber) {        this.caliber = caliber;    }    public double getWeight() {        return weight;    }    public void setWeight(double weight) {        this.weight = weight;    }    @Override    public String toString() {        return "BulletEntity [id=" + id + ", caliber=" + caliber + ", weight=" + weight + "]";    }}

配置文件:BulletEntity.hbm.xml

<?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.zh.entity">    <class name="BulletEntity" table="t_bullet">        <!-- 映射标识属性(属性) -->        <id name="id" column="id" type="int">            <!-- 主键生成策略(自增主键) -->            <generator class="native" />        </id>        <!-- 映射普通属性 -->        <property name="caliber" column="caliber"></property>        <property name="weight" column="weight"></property>    </class></hibernate-mapping>

3、在总配置文件hibernate.cfg.xml里添加配置映射文件

这里写图片描述

4、创建测试类:HibernateTest

public class HibernateTest2 {    public static void main(String[] args) {        HibernateTest test=new HibernateTest();        test.singleOneToMany();    }    //单向一对多测试        public void singleOneToMany() {            //开启会话            Session session=HibernatUtil.getSession();            //打开事物            Transaction transaction=session.beginTransaction();            /**             * 实例化手枪类             */            GunEntity gunEntity = new GunEntity();            gunEntity.setType("手枪");            /**             * 实例化子弹类1             */            BulletEntity bullet=new BulletEntity();            bullet.setCaliber(0.5);            bullet.setWeight(2.0);            session.persist(bullet);            /**             * 实例化子弹类2             */            BulletEntity bullet2=new BulletEntity();            bullet2.setCaliber(0.3);            bullet2.setWeight(1.8);            session.persist(bullet2);            /**             * 将枪与子弹相关联             */            Set<BulletEntity> bullets=new HashSet<>();            gunEntity.setBullets(bullets);            gunEntity.getBullets().add(bullet);            gunEntity.getBullets().add(bullet2);            //保存到数据库            session.persist(gunEntity);            //提交事物            transaction.commit();            //关闭会话            HibernatUtil.closeSession(session);        }}

点击运行,测试成功!
这里写图片描述
看看数据库自动生成的数据:
这里写图片描述这里写图片描述

原创粉丝点击