spring4.x + hibernate4.x 配置詳解

spring4.x + hibernate4.x 配置詳解

關於spring和hibernate的使用以及特徵等等,在此不再囉嗦,相信大家也都知道,或者去搜索一下即可。

本篇博文的內容主要是我最近整理的關於spring4.x 和 hibernate 4.x 相關配置和使用方式,當然spring3.x以及hibernate4.x也可以借鑑。

 

首先是配置文件 web.xml 增加以下代碼即可

<!-- 加載spring相關的配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/applicationContext.xml</param-value>
    </context-param>
    
    <!-- 啓用spring監聽 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>


 

然後建立 applicationContext.xml 文件 ,src下。 文件內容如下,註釋我儘量寫的很詳細

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">
    <!-- 引入properties文件 -->
    <context:property-placeholder location="classpath*:/appConfig.properties" />
    <!-- 定義數據庫連接池數據源bean destroy-method="close"的作用是當數據庫連接不使用的時候,就把該連接重新放到數據池中,方便下次使用調用 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <!-- 設置JDBC驅動名稱 -->
        <property name="driverClass" value="${jdbc.driver}" />
        <!-- 設置JDBC連接URL -->
        <property name="jdbcUrl" value="${jdbc.url}" />
        <!-- 設置數據庫用戶名 -->
        <property name="user" value="${jdbc.username}" />
        <!-- 設置數據庫密碼 -->
        <property name="password" value="${jdbc.password}" />
        <!-- 設置連接池初始值 -->
        <property name="initialPoolSize" value="5" />
    </bean>

    <!-- 配置sessionFactory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <!-- 數據源 -->
        <property name="dataSource" ref="dataSource" />

        <!-- hibernate的相關屬性配置 -->
        <property name="hibernateProperties">
            <value>
                <!-- 設置數據庫方言 -->
                hibernate.dialect=org.hibernate.dialect.MySQLDialect
                <!-- 設置自動創建|更新|驗證數據庫表結構 -->
                hibernate.hbm2ddl.auto=update
                <!-- 是否在控制檯顯示sql -->
                hibernate.show_sql=true
                <!-- 是否格式化sql,優化顯示 -->
                hibernate.format_sql=true
                <!-- 是否開啓二級緩存 -->
                hibernate.cache.use_second_level_cache=false
                <!-- 是否開啓查詢緩存 -->
                hibernate.cache.use_query_cache=false
                <!-- 數據庫批量查詢最大數 -->
                hibernate.jdbc.fetch_size=50
                <!-- 數據庫批量更新、添加、刪除操作最大數 -->
                hibernate.jdbc.batch_size=50
                <!-- 是否自動提交事務 -->
                hibernate.connection.autocommit=true
                <!-- 指定hibernate在何時釋放JDBC連接 -->
                hibernate.connection.release_mode=auto
                <!-- 創建session方式 hibernate4.x 的方式 -->
                hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
                <!-- javax.persistence.validation.mode默認情況下是auto的,就是說如果不設置的話它是會自動去你的classpath下面找一個bean-validation**包 
                    所以把它設置爲none即可 -->
                javax.persistence.validation.mode=none
            </value>
        </property>
        <!-- 自動掃描實體對象 tdxy.bean的包結構中存放實體類 -->
        <property name="packagesToScan" value="tdxy.bean" />
    </bean>
    <!-- 定義事務管理 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    
    <!-- 定義 Autowired  自動注入 bean -->
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> 
    
    <!-- 掃描有註解的文件  base-package 包路徑 -->
    <context:component-scan base-package="tdxy"/>
    
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 事務執行方式
                REQUIRED:指定當前方法必需在事務環境中運行,
                如果當前有事務環境就加入當前正在執行的事務環境,
                如果當前沒有事務,就新建一個事務。
                這是默認值。 
             -->
            <tx:method name="create*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <tx:method name="del*" propagation="REQUIRED" />
            <tx:method name="import*" propagation="REQUIRED" />
            <!-- 
                指定當前方法以非事務方式執行操作,如果當前存在事務,就把當前事務掛起,等我以非事務的狀態運行完,再繼續原來的事務。 
                查詢定義即可
                read-only="true"  表示只讀
             -->
            <tx:method name="*" propagation="NOT_SUPPORTED" read-only="true" />
        </tx:attributes>
    </tx:advice>

    <!-- 定義切面,在 * tdxy.*.service.*ServiceImpl.*(..) 中執行有關的hibernate session的事務操作 -->
    <aop:config>
        <aop:pointcut id="serviceOperation" expression="execution(* tdxy.*.service.*Service.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
    </aop:config>
    
</beans>


 

applicationContext.xml 文件引用了一個properties文件 ,該文件也在src下,appConfig.properties 內容可以自己定義

########################數據庫連接信息#############
jdbc.username = root
jdbc.password = admin
jdbc.url = jdbc:mysql://localhost:3306/tdxy?useUnicode=true&characterEncoding=UTF-8
jdbc.driver = com.mysql.jdbc.Driver


自己寫了一個test用的basedao 

package tdxy.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * 
 * @Title: BaseDao.java
 * @Package tdxy.dao
 * @Description: TODO(baseDao 數據庫操作實現類)
 * @author dapeng
 * @date 2014年5月7日 下午5:09:22
 * @version V1.0
 */
@Repository
public class BaseDao {

    /**
     * Autowired 自動裝配 相當於get() set()
     */
    @Autowired
    protected SessionFactory sessionFactory;

    /**
     * gerCurrentSession 會自動關閉session,使用的是當前的session事務
     * 
     * @return
     */
    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    /**
     * openSession 需要手動關閉session 意思是打開一個新的session
     * 
     * @return
     */
    public Session getNewSession() {
        return sessionFactory.openSession();
    }

    public void flush() {
        getSession().flush();
    }

    public void clear() {
        getSession().clear();
    }

    /**
     * 根據 id 查詢信息
     * 
     * @param id
     * @return
     */
    @SuppressWarnings("rawtypes")
    public Object load(Class c, String id) {
        Session session = getSession();
        return session.get(c, id);
    }

    /**
     * 獲取所有信息
     * 
     * @param c 
     *        
     * @return
     */
    @SuppressWarnings({ "rawtypes" })
    public List getAllList(Class c) {
        String hql = "from " + c.getName();
        Session session = getSession();
        return session.createQuery(hql).list();
    }

    /**
     * 獲取總數量
     * 
     * @param c
     * @return
     */
    @SuppressWarnings("rawtypes")
    public Long getTotalCount(Class c) {
        Session session = getNewSession();
        String hql = "select count(*) from " + c.getName();
        Long count = (Long) session.createQuery(hql).uniqueResult();
        session.close();
        return count != null ? count.longValue() : 0;
    }

    /**
     * 保存
     * 
     * @param bean 
     *            
     */
    public void save(Object bean) {
        try {
            Session session = getNewSession();
            session.save(bean);
            session.flush();
            session.clear();
            session.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新
     * 
     * @param bean 
     *            
     */
    public void update(Object bean) {
        Session session = getNewSession();
        session.update(bean);
        session.flush();
        session.clear();
        session.close();
    }

    /**
     * 刪除
     * 
     * @param bean 
     *            
     */
    public void delete(Object bean) {
        Session session = getNewSession();
        session.delete(bean);
        session.flush();
        session.clear();
        session.close();
    }

    /**
     * 根據ID刪除
     * 
     * @param c 類
     *            
     * @param id ID
     *            
     */
    @SuppressWarnings({ "rawtypes" })
    public void delete(Class c, String id) {
        Session session = getNewSession();
        Object obj = session.get(c, id);
        session.delete(obj);
        flush();
        clear();
    }

    /**
     * 批量刪除
     * 
     * @param c 類
     *            
     * @param ids ID 集合
     *            
     */
    @SuppressWarnings({ "rawtypes" })
    public void delete(Class c, String[] ids) {
        for (String id : ids) {
            Object obj = getSession().get(c, id);
            if (obj != null) {
                getSession().delete(obj);
            }
        }
    }

}


 

不知大家有沒有注意 applicationContext.xml 這樣一句代碼

<!-- 設置自動創建|更新|驗證數據庫表結構 -->
    hibernate.hbm2ddl.auto=update

這個意思是 只要在實體bean指定了entity,那麼在數據庫會自動創建對應的表和表結構

 

test用的一個實體bean

package tdxy.bean;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.Id;

/**
 * 
 * @ClassName: UserInfoBean
 * @Description: TODO(用戶信息類)
 * @author dapeng
 * @date 2014年5月7日 上午12:13:44
 * @version V1.0
 * 
 */
@Entity
public class UserInfoBean implements Serializable {

    private static final long serialVersionUID = 7280747949998651159L;

    @Id
    private String id;
    /**
     * 暱稱
     */
    private String nickName;
    private String pwd;
    /**
     * 等級
     * 
     */
    private String level;

    /**
     * 經驗值
     */
    private String emValue;
    /**
     * 性別(0 男 1女)
     */
    private String sex;
    private String birthday;
    private String qq;
    private String email;
    /**
     * 頭像
     */
    private String img;
    /**
     * 所在地
     */
    private String address;
    /**
     * 簽名
     */
    private String qmd;

    public String getId() {
        return id;
    }

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

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getLevel() {
        return level;
    }

    public void setLevel(String level) {
        this.level = level;
    }

    public String getEmValue() {
        return emValue;
    }

    public void setEmValue(String emValue) {
        this.emValue = emValue;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public String getQq() {
        return qq;
    }

    public void setQq(String qq) {
        this.qq = qq;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getImg() {
        return img;
    }

    public void setImg(String img) {
        this.img = img;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getQmd() {
        return qmd;
    }

    public void setQmd(String qmd) {
        this.qmd = qmd;
    }

}

當應用成功啓動之後,數據庫會出現表和結構,即剛纔定義的bean是一樣的,大家可以自己查看一下即可。

 

 

以下是test的Service

package tdxy.user.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import tdxy.bean.UserInfoBean;
import tdxy.dao.BaseDao;
import tdxy.util.TdxyUtil;

@Service
public class UserInfoService {

    @Autowired
    private BaseDao baseDao;

    public UserInfoBean queryUserInfoById(String id) {
        return (UserInfoBean) baseDao.load(UserInfoBean.class, id);
    }

    public void addUserInfo(UserInfoBean userInfo) {
        try {
            userInfo.setId(TdxyUtil.getId());
            userInfo.setAddress("32132");
            baseDao.save(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

配置過程到此結束,希望大家一起討論共同進步。

 

 轉載自 http://www.cnblogs.com/anhelida
發佈了25 篇原創文章 · 獲贊 9 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章