spring4如何整合 hibernate4 配置详解

  1. 关于springhibernate的使用以及特征等等,在此不再啰嗦,相信大家也都知道,或者去搜索一下即可。
  2. 本篇博文的内容主要是我最近整理的关于spring4.x 和 hibernate 4.x 相关配置和使用方式,当然spring3.x以及hibernate4.x也可以借鉴。

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

  4. <!-- 加载spring相关的配置文件 -->
  5.     <context-param>
  6.         <param-name>contextConfigLocation</param-name>
  7.         <param-value>classpath*:/applicationContext.xml</param-value>
  8.     </context-param>
  9.     
  10.     <!-- 启用spring监听 -->
  11.     <listener>
  12.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  13.     </listener>
  14.     


  15. 然后建立 applicationContext.xml 文件 ,src下。 文件内容如下,注释我尽量写的很详细

  16. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  17.     xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
  18.     xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
  19.     xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
  20.     xsi:schemaLocation="http://www.springframework.org/schema/beans 
  21.        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  22.        http://www.springframework.org/schema/aop
  23.        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  24.        http://www.springframework.org/schema/context
  25.        http://www.springframework.org/schema/context/spring-context-4.0.xsd
  26.        http://www.springframework.org/schema/tx
  27.        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
  28.        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">
  29.     <!-- 引入properties文件 -->
  30.     <context:property-placeholder location="classpath*:/appConfig.properties" />
  31.     <!-- 定义数据库连接池数据源bean destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用 -->
  32.     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
  33.         destroy-method="close">
  34.         <!-- 设置JDBC驱动名称 -->
  35.         <property name="driverClass" value="${jdbc.driver}" />
  36.         <!-- 设置JDBC连接URL -->
  37.         <property name="jdbcUrl" value="${jdbc.url}" />
  38.         <!-- 设置数据库用户名 -->
  39.         <property name="user" value="${jdbc.username}" />
  40.         <!-- 设置数据库密码 -->
  41.         <property name="password" value="${jdbc.password}" />
  42.         <!-- 设置连接池初始值 -->
  43.         <property name="initialPoolSize" value="5" />
  44.     </bean>

  45.     <!-- 配置sessionFactory -->
  46.     <bean id="sessionFactory"
  47.         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
  48.         <!-- 数据源 -->
  49.         <property name="dataSource" ref="dataSource" />

  50.         <!-- hibernate的相关属性配置 -->
  51.         <property name="hibernateProperties">
  52.             <value>
  53.                 <!-- 设置数据库方言 -->
  54.                 hibernate.dialect=org.hibernate.dialect.MySQLDialect
  55.                 <!-- 设置自动创建|更新|验证数据库表结构 -->
  56.                 hibernate.hbm2ddl.auto=update
  57.                 <!-- 是否在控制台显示sql -->
  58.                 hibernate.show_sql=true
  59.                 <!-- 是否格式化sql,优化显示 -->
  60.                 hibernate.format_sql=true
  61.                 <!-- 是否开启二级缓存 -->
  62.                 hibernate.cache.use_second_level_cache=false
  63.                 <!-- 是否开启查询缓存 -->
  64.                 hibernate.cache.use_query_cache=false
  65.                 <!-- 数据库批量查询最大数 -->
  66.                 hibernate.jdbc.fetch_size=50
  67.                 <!-- 数据库批量更新、添加、删除操作最大数 -->
  68.                 hibernate.jdbc.batch_size=50
  69.                 <!-- 是否自动提交事务 -->
  70.                 hibernate.connection.autocommit=true
  71.                 <!-- 指定hibernate在何时释放JDBC连接 -->
  72.                 hibernate.connection.release_mode=auto
  73.                 <!-- 创建session方式 hibernate4.x 的方式 -->
  74.                 hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
  75.                 <!-- javax.persistence.validation.mode默认情况下是auto的,就是说如果不设置的话它是会自动去你的classpath下面找一个bean-validation**包 
  76.                     所以把它设置为none即可 -->
  77.                 javax.persistence.validation.mode=none
  78.             </value>
  79.         </property>
  80.         <!-- 自动扫描实体对象 tdxy.bean的包结构中存放实体类 -->
  81.         <property name="packagesToScan" value="tdxy.bean" />
  82.     </bean>
  83.     <!-- 定义事务管理 -->
  84.     <bean id="transactionManager"
  85.         class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  86.         <property name="sessionFactory" ref="sessionFactory" />
  87.     </bean>
  88.     
  89.     <!-- 定义 Autowired  自动注入 bean -->
  90.     <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> 
  91.     
  92.     <!-- 扫描有注解的文件  base-package 包路径 -->
  93.     <context:component-scan base-package="tdxy"/>
  94.     
  95.     <tx:advice id="txAdvice" transaction-manager="transactionManager">
  96.         <tx:attributes>
  97.             <!-- 事务执行方式
  98.                 REQUIRED:指定当前方法必需在事务环境中运行,
  99.                 如果当前有事务环境就加入当前正在执行的事务环境,
  100.                 如果当前没有事务,就新建一个事务。
  101.                 这是默认值。 
  102.              -->
  103.             <tx:method name="create*" propagation="REQUIRED" />
  104.             <tx:method name="save*" propagation="REQUIRED" />
  105.             <tx:method name="add*" propagation="REQUIRED" />
  106.             <tx:method name="update*" propagation="REQUIRED" />
  107.             <tx:method name="remove*" propagation="REQUIRED" />
  108.             <tx:method name="del*" propagation="REQUIRED" />
  109.             <tx:method name="import*" propagation="REQUIRED" />
  110.             <!-- 
  111.                 指定当前方法以非事务方式执行操作,如果当前存在事务,就把当前事务挂起,等我以非事务的状态运行完,再继续原来的事务。 
  112.                 查询定义即可
  113.                 read-only="true"  表示只读
  114.              -->
  115.             <tx:method name="*" propagation="NOT_SUPPORTED" read-only="true" />
  116.         </tx:attributes>
  117.     </tx:advice>

  118.     <!-- 定义切面,在 * tdxy.*.service.*ServiceImpl.*(..) 中执行有关的hibernate session的事务操作 -->
  119.     <aop:config>
  120.         <aop:pointcut id="serviceOperation" expression="execution(* tdxy.*.service.*Service.*(..))" />
  121.         <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
  122.     </aop:config>
  123.     
  124. </beans>



  125. applicationContext.xml 文件引用了一个properties文件 ,该文件也在src下,appConfig.properties 内容可以自己定义
  126. 1
  127. 2
  128. 3
  129. 4
  130. 5
  131. ########################数据库连接信息#############
  132. jdbc.username = root
  133. jdbc.password = admin
  134. jdbc.url = jdbc:mysql://localhost:3306/tdxy?useUnicode=true&characterEncoding=UTF-8
  135. jdbc.driver = com.mysql.jdbc.Driver


  136. 自己写了一个test用的basedao 

  137. package tdxy.dao;

  138. import java.util.List;

  139. import org.hibernate.Session;
  140. import org.hibernate.SessionFactory;
  141. import org.springframework.beans.factory.annotation.Autowired;
  142. import org.springframework.stereotype.Repository;

  143. /**

  144. * @Title: BaseDao.java
  145. * @Package tdxy.dao
  146. * @Description: TODO(baseDao 数据库操作实现类)
  147. * @author dapeng
  148. * @date 2014年5月7日 下午5:09:22
  149. * @version V1.0
  150. */
  151. @Repository
  152. public class BaseDao {

  153.     /**
  154.      * Autowired 自动装配 相当于get() set()
  155.      */
  156.     @Autowired
  157.     protected SessionFactory sessionFactory;

  158.     /**
  159.      * gerCurrentSession 会自动关闭session,使用的是当前的session事务
  160.      * 
  161.      * @return
  162.      */
  163.     public Session getSession() {
  164.         return sessionFactory.getCurrentSession();
  165.     }

  166.     /**
  167.      * openSession 需要手动关闭session 意思是打开一个新的session
  168.      * 
  169.      * @return
  170.      */
  171.     public Session getNewSession() {
  172.         return sessionFactory.openSession();
  173.     }

  174.     public void flush() {
  175.         getSession().flush();
  176.     }

  177.     public void clear() {
  178.         getSession().clear();
  179.     }

  180.     /**
  181.      * 根据 id 查询信息
  182.      * 
  183.      * @param id
  184.      * @return
  185.      */
  186.     @SuppressWarnings("rawtypes")
  187.     public Object load(Class c, String id) {
  188.         Session session = getSession();
  189.         return session.get(c, id);
  190.     }

  191.     /**
  192.      * 获取所有信息
  193.      * 
  194.      * @param c 
  195.      *        
  196.      * @return
  197.      */
  198.     @SuppressWarnings({ "rawtypes" })
  199.     public List getAllList(Class c) {
  200.         String hql = "from " + c.getName();
  201.         Session session = getSession();
  202.         return session.createQuery(hql).list();
  203.     }

  204.     /**
  205.      * 获取总数量
  206.      * 
  207.      * @param c
  208.      * @return
  209.      */
  210.     @SuppressWarnings("rawtypes")
  211.     public Long getTotalCount(Class c) {
  212.         Session session = getNewSession();
  213.         String hql = "select count(*) from " + c.getName();
  214.         Long count = (Long) session.createQuery(hql).uniqueResult();
  215.         session.close();
  216.         return count != null ? count.longValue() : 0;
  217.     }

  218.     /**
  219.      * 保存
  220.      * 
  221.      * @param bean 
  222.      *            
  223.      */
  224.     public void save(Object bean) {
  225.         try {
  226.             Session session = getNewSession();
  227.             session.save(bean);
  228.             session.flush();
  229.             session.clear();
  230.             session.close();
  231.         } catch (Exception e) {
  232.             e.printStackTrace();
  233.         }
  234.     }

  235.     /**
  236.      * 更新
  237.      * 
  238.      * @param bean 
  239.      *            
  240.      */
  241.     public void update(Object bean) {
  242.         Session session = getNewSession();
  243.         session.update(bean);
  244.         session.flush();
  245.         session.clear();
  246.         session.close();
  247.     }

  248.     /**
  249.      * 删除
  250.      * 
  251.      * @param bean 
  252.      *            
  253.      */
  254.     public void delete(Object bean) {
  255.         Session session = getNewSession();
  256.         session.delete(bean);
  257.         session.flush();
  258.         session.clear();
  259.         session.close();
  260.     }

  261.     /**
  262.      * 根据ID删除
  263.      * 
  264.      * @param c 类
  265.      *            
  266.      * @param id ID
  267.      *            
  268.      */
  269.     @SuppressWarnings({ "rawtypes" })
  270.     public void delete(Class c, String id) {
  271.         Session session = getNewSession();
  272.         Object obj = session.get(c, id);
  273.         session.delete(obj);
  274.         flush();
  275.         clear();
  276.     }

  277.     /**
  278.      * 批量删除
  279.      * 
  280.      * @param c 类
  281.      *            
  282.      * @param ids ID 集合
  283.      *            
  284.      */
  285.     @SuppressWarnings({ "rawtypes" })
  286.     public void delete(Class c, String[] ids) {
  287.         for (String id : ids) {
  288.             Object obj = getSession().get(c, id);
  289.             if (obj != null) {
  290.                 getSession().delete(obj);
  291.             }
  292.         }
  293.     }

  294. }



  295. 不知大家有没有注意 applicationContext.xml 这样一句代码
  296. <!-- 设置自动创建|更新|验证数据库表结构 -->
  297.     hibernate.hbm2ddl.auto=update
  298. 这个意思是 只要在实体bean指定了entity,那么在数据库会自动创建对应的表和表结构


  299. test用的一个实体bean

  300. package tdxy.bean;

  301. import java.io.Serializable;

  302. import javax.persistence.Entity;
  303. import javax.persistence.Id;

  304. /**

  305. * @ClassName: UserInfoBean
  306. * @Description: TODO(用户信息类)
  307. * @author dapeng
  308. * @date 2014年5月7日 上午12:13:44
  309. * @version V1.0

  310. */
  311. @Entity
  312. public class UserInfoBean implements Serializable {

  313.     private static final long serialVersionUID = 7280747949998651159L;

  314.     @Id
  315.     private String id;
  316.     /**
  317.      * 昵称
  318.      */
  319.     private String nickName;
  320.     private String pwd;
  321.     /**
  322.      * 等级
  323.      * 
  324.      */
  325.     private String level;

  326.     /**
  327.      * 经验值
  328.      */
  329.     private String emValue;
  330.     /**
  331.      * 性别(0 男 1女)
  332.      */
  333.     private String sex;
  334.     private String birthday;
  335.     private String qq;
  336.     private String email;
  337.     /**
  338.      * 头像
  339.      */
  340.     private String img;
  341.     /**
  342.      * 所在地
  343.      */
  344.     private String address;
  345.     /**
  346.      * 签名
  347.      */
  348.     private String qmd;

  349.     public String getId() {
  350.         return id;
  351.     }

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

  355.     public String getNickName() {
  356.         return nickName;
  357.     }

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

  361.     public String getPwd() {
  362.         return pwd;
  363.     }

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

  367.     public String getLevel() {
  368.         return level;
  369.     }

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

  373.     public String getEmValue() {
  374.         return emValue;
  375.     }

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

  379.     public String getSex() {
  380.         return sex;
  381.     }

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

  385.     public String getBirthday() {
  386.         return birthday;
  387.     }

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

  391.     public String getQq() {
  392.         return qq;
  393.     }

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

  397.     public String getEmail() {
  398.         return email;
  399.     }

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

  403.     public String getImg() {
  404.         return img;
  405.     }

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

  409.     public String getAddress() {
  410.         return address;
  411.     }

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

  415.     public String getQmd() {
  416.         return qmd;
  417.     }

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

  421. }


  422. 当应用成功启动之后,数据库会出现表和结构,即刚才定义的bean是一样的,大家可以自己查看一下即可。


  423. 以下是test的Service

  424. package tdxy.user.service;

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

  427. import tdxy.bean.UserInfoBean;
  428. import tdxy.dao.BaseDao;
  429. import tdxy.util.TdxyUtil;

  430. @Service
  431. public class UserInfoService {

  432.     @Autowired
  433.     private BaseDao baseDao;

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

  437.     public void addUserInfo(UserInfoBean userInfo) {
  438.         try {
  439.             userInfo.setId(TdxyUtil.getId());
  440.             userInfo.setAddress("32132");
  441.             baseDao.save(userInfo);
  442.         } catch (Exception e) {
  443.             e.printStackTrace();
  444.         }
  445.     }
  446. }




  447. 配置过程到此结束,希望大家一起讨论共同进步。
原帖地址:spring4如何整合 hibernate4 配置详解
http://www.52itstyle.com/thread-513-1-1.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值