Hibernate 多表關聯

hibernate中能夠一次對多個表進行數據插入,這種插入相似java

 

Hibernate的關聯映射關係有:
多對一 ---- many-to-one
一對多 ---- one-to-many
一對一 ---- one-to-one
多對多 ---- many-to-manyspring

比較經常使用的是多對一和一對一關聯映射多對一關聯映射:sql

場景:用戶和組;從用戶角度來看,多個用戶屬於一個組(多對一關聯)
使用Hibernate開發的思路:先創建對象模型,把實體抽取出來。目前兩個實體:用戶和組兩個實體,多個學生擁有同一個地址
,全部用戶實體中應該有一個持有組的引用
數據庫

看實體類:緩存

package com.entity;

/**
 * Student entity. @author MyEclipse Persistence Tools
 */

public class Student implements java.io.Serializable {

    // Fields

    private Integer id;
    private String name;
    private Integer addid;
    
    private Adrress adss;

    // Constructors

    public Adrress getAdss() {
        return adss;
    }

    public void setAdss(Adrress adss) {
        this.adss = adss;
    }

    /** default constructor */
    public Student() {
    }

    /** full constructor */
    public Student(String name, Integer addid) {
        this.name = name;
        this.addid = addid;
    }

    // Property accessors

    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAddid() {
        return this.addid;
    }

    public void setAddid(Integer addid) {
        this.addid = addid;
    }

}

 

 

package com.entity;

/**
 * Adrress entity. @author MyEclipse Persistence Tools
 */

public class Adrress implements java.io.Serializable {

    // Fields

    private Integer idAdrress;
    private String detail;

    // Constructors

    /** default constructor */
    public Adrress() {
    }

    /** full constructor */
    public Adrress(String detail) {
        this.detail = detail;
    }

    // Property accessors

    public Integer getIdAdrress() {
        return this.idAdrress;
    }

    public void setIdAdrress(Integer idAdrress) {
        this.idAdrress = idAdrress;
    }

    public String getDetail() {
        return this.detail;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }

}

 

hibernate 映射表的內容session

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Mapping file autogenerated by MyEclipse Persistence Tools -->
<hibernate-mapping>
    <class name="com.entity.Student" table="student" catalog="test">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="increment"></generator>
        </id>
        <property name="name" type="java.lang.String">
            <column name="Name" length="45" />
        </property>
        
        <many-to-one name="adss" column="addid" cascade="save-update" class="com.entity.Adrress"></many-to-one>
        <!-- name 屬性表示Student類中的屬性,column爲對應的表中的和adrress表中主鍵關聯的名稱, 也就是將address類中的主鍵的值做爲addid的值插入表student中 -->
    </class>
</hibernate-mapping>

 

Spring中配置了事務,利用的是註解的方式app

    <bean id="sessionFactoryt" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

        <!-- 也能夠這樣配 -->
        <!-- <property name="configLocation"> <value>classpath:hibernate.cfg.xml</value> </property> -->
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <property name="hibernateProperties">
            <props>

                <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect <!-- 數據庫所用的sql語句 -->
                </prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>

                <prop key="hibernate.cache.use_second_level_cache">true</prop>         <!--啓用二級緩存 -->
                <prop key="hibernate.cache.use_query_cache">false</prop>              <!--是否啓動查詢緩存 -->
                <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>    <!--指定緩存類 -->

            </props>
        </property>
        <!-- <property name="packagesToScan" value="com.*" /> 爲何不起做用,別人的就能夠 -->

        <!-- <property name="mappingResources"> <list> <value>com/entity/Admin.hbm.xml</value> <value>com/entity/Userinfo.hbm.xml</value> </list> </property> -->

        <property name="mappingDirectoryLocations">
            <list>
                <value>com/entity</value>
            </list>
        </property>
    </bean>
<bean id="tm" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactoryt" />
    </bean>

 




<
bean id="userDao" class="com.dao.imp.UserDao"> <property name="sessionFactory" ref="sessionFactoryt" /> </bean> <tx:advice id="txAdvice" transaction-manager="tm"> <tx:attributes> <!-- 配置被weave織入的那些方法, 使用的傳播行爲和隔離級別 --> <tx:method name="*" propagation="REQUIRED" isolation="READ_COMMITTED" /> </tx:attributes> </tx:advice> <!-- 6.aop:config--> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.dao.imp.UserDao.*(..))" /> </aop:config> <tx:annotation-driven transaction-manager="tm" />

 

測試代碼ide

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); UserDao ud1=(UserDao)ctx.getBean("userDao");//改爲userDao就是註解方式的代理

System.out.println("OK");
ud1.insert("liu");測試

 

 

 

UserDao中的插入數據,由於沒有用到接口Spring採用的CGLib代理。this

 

public void insert(String s) { System.out.println("插入數據!"); // sessionFactory.openSession().save(arg0)
 Admin adm = new Admin(); Session sess = sessionFactory.getCurrentSession(); Adrress ad = new Adrress(); ad.setDetail("shan xi"); Student st = new Student(); st.setName("liuyu"); st.setAdss(ad); sess.save(st); //Transaction tx = sess.beginTransaction(); //tx.begin();
            /*Userinfo user = new Userinfo(); System.out.println("查找數據!"); // TODO Auto-generated method stub }

 

 

若是成功,就能夠看到以下的語句:

插入數據! Hibernate: select
        max(id) from student Hibernate: select
        max(idAdrress) from adrress 插入數據! Hibernate: insert 
    into test.adrress (detail, idAdrress) values (?, ?) Hibernate: insert 
    into test.student (Name, addid, id) values (?, ?, ?)

 

回到數據庫中也能夠看到結果。

 

參考:http://blog.csdn.net/fengxuezhiye/article/details/7369786

相關文章
相關標籤/搜索