Hibernate一对多单向(双向)关联映射

(1)、编写配置文件

  Hibernate通过读写默认的XML配置文件hibernate.cfg.xml加载数据库配置信息、代码如下: 

<hibernate-configuration>
 	<session-factory>
		<!-- 数据库驱动 -->
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<!-- 数据库连接的URL -->
		<property name="connection.url">jdbc:mysql://localhost:3306/db_database14</property>
		<!-- 数据库连接用户名 -->
		<property name="connection.username">root</property>
		<!-- 数据库连接密码 -->
		<property name="connection.password"></property>
		<!-- Hibernate方言 -->
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- 打印SQL语句 -->
		<property name="show_sql">true</property>
		<!-- 映射文件  -->
		<mapping resource="com/wgh/model/Book.hbm.xml" />
		<mapping resource="com/wgh/model/Category.hbm.xml" />		
 	</session-factory>
 </hibernate-configuration>

(2)、编写持久化类

  持久化类是Hibernate操作的对象、它与数据库中的数据表相对应

(双向)
/**
* 图书类别持久化类 */ public class Category { private Integer id; //ID private String name; //类别名称 private Set<Book> books; //Set集合(类别中的所有图书) 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 Set<Book> getBooks() { return books; } public void setBooks(Set<Book> books) { this.books = books; } }
(单向)
/**
* 图书类别持久化类 */ public class Category { private Integer id; //ID private String name; //类别名称 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 class Book {
    private Integer id;            //ID
    private String name;        //图书名称
    private String author;
    private Category category;    //所属类别
    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 String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public Category getCategory() {
        return category;
    }
    public void setCategory(Category category) {
        this.category = category;
    }
}

(3)、编写映射文件

(双向)
<hibernate-mapping package="com.wgh.model"> <class name="Category" table="tb_Category_manytoone3"> <id name="id"> <generator class="native"/> </id> <property name="name" not-null="true" length="200" /> <!-- 一对多映射 --> <set name="books"> <key column="categoryId"/> <one-to-many class="Book"/> </set> </class> </hibernate-mapping>
(单向)
<hibernate-mapping package="com.wgh.model"> <class name="Category" table="tb_Category_manytoone0"> <id name="id"> <generator class="native"/> </id> <property name="name" not-null="true" length="200" /> </class> </hibernate-mapping>
<hibernate-mapping package="com.wgh.model">
    <class name="Book" table="tb_book_manytoone0">
        <!-- 主键 -->
        <id name="id">
            <generator class="native"/>
        </id>
        <!-- 图书名称 -->
        <property name="name" not-null="true" length="200" />
        <!-- 作者 -->
        <property name="author" not-null="true" length="50"/>
        <!-- 多对一关联映射 -->
        <many-to-one name="category" class="Category">
            <!-- 映射的字段 -->
            <column name="categoryId"/>
        </many-to-one>
    </class>
</hibernate-mapping>

(4)、编写Hibernate的工具类

package com.wgh.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static SessionFactory sessionFactory = null; // SessionFactory对象
    // 静态块
    static {
        try {
            Configuration cfg = new Configuration().configure(); // 加载Hibernate配置文件
            sessionFactory = cfg
                    .buildSessionFactory(new ServiceRegistryBuilder().applySettings(cfg.getProperties())
                            .buildServiceRegistry());
        } catch (Exception e) {
            System.err.println("创建会话工厂失败");
            e.printStackTrace();
        }
    }

    /**
     * 获取Session
     * 
     * @return Session
     * @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        if (session == null || !session.isOpen()) {
            if (sessionFactory == null) {
                rebuildSessionFactory();
            }
            session = (sessionFactory != null) ? sessionFactory.openSession()
                    : null;
            threadLocal.set(session);
        }
        return session;
    }

    /**
     * 重建会话工厂
     */
    public static void rebuildSessionFactory() {
        try {
            Configuration cfg = new Configuration().configure(); // 加载Hibernate配置文件
            sessionFactory = cfg
                    .buildSessionFactory(new ServiceRegistryBuilder().applySettings(cfg.getProperties())
                            .buildServiceRegistry());
        } catch (Exception e) {
            System.err.println("创建会话工厂失败");
            e.printStackTrace();
        }
    }

    /**
     * 获取SessionFactory对象
     * 
     * @return SessionFactory对象
     */
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     * 关闭Session
     * 
     * @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);
        if (session != null) {
            session.close(); // 关闭Session
        }
    }
}

 

 

 

  

posted @ 2016-12-26 21:45  知晓的老巢  阅读(444)  评论(0编辑  收藏  举报