spring4.x + hibernate4.x 配置详解

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

本篇博文的内容主要是我最近整理的关于spring4.x 和 hibernate 4.x 相关配置和使用方式,当然spring3.x以及hibernate4.x也可以借鉴。

本文由上海java培训机构推荐阅读,更多精彩请浏览上海it培训官网。

 

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

Xml代码   收藏代码
  1. <!-- 加载spring相关的配置文件 -->  
  2.     <context-param>  
  3.         <param-name>contextConfigLocation</param-name>  
  4.         <param-value>classpath*:/applicationContext.xml</param-value>  
  5.     </context-param>  
  6.       
  7.     <!-- 启用spring监听 -->  
  8.     <listener>  
  9.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  10.     </listener>  

 

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

Xml代码   收藏代码
  1. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.     xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"  
  3.     xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"  
  4.     xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  6.        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
  7.        http://www.springframework.org/schema/aop  
  8.        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
  9.        http://www.springframework.org/schema/context  
  10.        http://www.springframework.org/schema/context/spring-context-4.0.xsd  
  11.        http://www.springframework.org/schema/tx  
  12.        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd  
  13.        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">  
  14.     <!-- 引入properties文件 -->  
  15.     <context:property-placeholder location="classpath*:/appConfig.properties" />  
  16.     <!-- 定义数据库连接池数据源bean destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用 -->  
  17.     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"  
  18.         destroy-method="close">  
  19.         <!-- 设置JDBC驱动名称 -->  
  20.         <property name="driverClass" value="${jdbc.driver}" />  
  21.         <!-- 设置JDBC连接URL -->  
  22.         <property name="jdbcUrl" value="${jdbc.url}" />  
  23.         <!-- 设置数据库用户名 -->  
  24.         <property name="user" value="${jdbc.username}" />  
  25.         <!-- 设置数据库密码 -->  
  26.         <property name="password" value="${jdbc.password}" />  
  27.         <!-- 设置连接池初始值 -->  
  28.         <property name="initialPoolSize" value="5" />  
  29.     </bean>  
  30.   
  31.     <!-- 配置sessionFactory -->  
  32.     <bean id="sessionFactory"  
  33.         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
  34.         <!-- 数据源 -->  
  35.         <property name="dataSource" ref="dataSource" />  
  36.   
  37.         <!-- hibernate的相关属性配置 -->  
  38.         <property name="hibernateProperties">  
  39.             <value>  
  40.                 <!-- 设置数据库方言 -->  
  41.                 hibernate.dialect=org.hibernate.dialect.MySQLDialect  
  42.                 <!-- 设置自动创建|更新|验证数据库表结构 -->  
  43.                 hibernate.hbm2ddl.auto=update  
  44.                 <!-- 是否在控制台显示sql -->  
  45.                 hibernate.show_sql=true  
  46.                 <!-- 是否格式化sql,优化显示 -->  
  47.                 hibernate.format_sql=true  
  48.                 <!-- 是否开启二级缓存 -->  
  49.                 hibernate.cache.use_second_level_cache=false  
  50.                 <!-- 是否开启查询缓存 -->  
  51.                 hibernate.cache.use_query_cache=false  
  52.                 <!-- 数据库批量查询最大数 -->  
  53.                 hibernate.jdbc.fetch_size=50  
  54.                 <!-- 数据库批量更新、添加、删除操作最大数 -->  
  55.                 hibernate.jdbc.batch_size=50  
  56.                 <!-- 是否自动提交事务 -->  
  57.                 hibernate.connection.autocommit=true  
  58.                 <!-- 指定hibernate在何时释放JDBC连接 -->  
  59.                 hibernate.connection.release_mode=auto  
  60.                 <!-- 创建session方式 hibernate4.x 的方式 -->  
  61.                 hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext  
  62.                 <!-- javax.persistence.validation.mode默认情况下是auto的,就是说如果不设置的话它是会自动去你的classpath下面找一个bean-validation**包   
  63.                     所以把它设置为none即可 -->  
  64.                 javax.persistence.validation.mode=none  
  65.             </value>  
  66.         </property>  
  67.         <!-- 自动扫描实体对象 tdxy.bean的包结构中存放实体类 -->  
  68.         <property name="packagesToScan" value="tdxy.bean" />  
  69.     </bean>  
  70.     <!-- 定义事务管理 -->  
  71.     <bean id="transactionManager"  
  72.         class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
  73.         <property name="sessionFactory" ref="sessionFactory" />  
  74.     </bean>  
  75.       
  76.     <!-- 定义 Autowired  自动注入 bean -->  
  77.     <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>   
  78.       
  79.     <!-- 扫描有注解的文件  base-package 包路径 -->  
  80.     <context:component-scan base-package="tdxy"/>  
  81.       
  82.     <tx:advice id="txAdvice" transaction-manager="transactionManager">  
  83.         <tx:attributes>  
  84.             <!-- 事务执行方式  
  85.                 REQUIRED:指定当前方法必需在事务环境中运行,  
  86.                 如果当前有事务环境就加入当前正在执行的事务环境,  
  87.                 如果当前没有事务,就新建一个事务。  
  88.                 这是默认值。   
  89.              -->  
  90.             <tx:method name="create*" propagation="REQUIRED" />  
  91.             <tx:method name="save*" propagation="REQUIRED" />  
  92.             <tx:method name="add*" propagation="REQUIRED" />  
  93.             <tx:method name="update*" propagation="REQUIRED" />  
  94.             <tx:method name="remove*" propagation="REQUIRED" />  
  95.             <tx:method name="del*" propagation="REQUIRED" />  
  96.             <tx:method name="import*" propagation="REQUIRED" />  
  97.             <!--   
  98.                 指定当前方法以非事务方式执行操作,如果当前存在事务,就把当前事务挂起,等我以非事务的状态运行完,再继续原来的事务。   
  99.                 查询定义即可  
  100.                 read-only="true"  表示只读  
  101.              -->  
  102.             <tx:method name="*" propagation="NOT_SUPPORTED" read-only="true" />  
  103.         </tx:attributes>  
  104.     </tx:advice>  
  105.   
  106.     <!-- 定义切面,在 * tdxy.*.service.*ServiceImpl.*(..) 中执行有关的hibernate session的事务操作 -->  
  107.     <aop:config>  
  108.         <aop:pointcut id="serviceOperation" expression="execution(* tdxy.*.service.*Service.*(..))" />  
  109.         <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />  
  110.     </aop:config>  
  111.       
  112. </beans>  

 

 

applicationContext.xml 文件引用了一个properties文件 ,该文件也在src下,appConfig.properties 内容可以自己定义

Java代码   收藏代码
  1. ########################数据库连接信息#############  
  2. jdbc.username = root  
  3. jdbc.password = admin  
  4. jdbc.url = jdbc:mysql://localhost:3306/tdxy?useUnicode=true&characterEncoding=UTF-8  
  5. jdbc.driver = com.mysql.jdbc.Driver  

 

 

自己写了一个test用的basedao 

Java代码   收藏代码
  1. package tdxy.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.hibernate.Session;  
  6. import org.hibernate.SessionFactory;  
  7. import org.springframework.beans.factory.annotation.Autowired;  
  8. import org.springframework.stereotype.Repository;  
  9.   
  10. /** 
  11.  *  
  12.  * @Title: BaseDao.java 
  13.  * @Package tdxy.dao 
  14.  * @Description: TODO(baseDao 数据库操作实现类) 
  15.  * @author dapeng 
  16.  * @date 2014年5月7日 下午5:09:22 
  17.  * @version V1.0 
  18.  */  
  19. @Repository  
  20. public class BaseDao {  
  21.   
  22.     /** 
  23.      * Autowired 自动装配 相当于get() set() 
  24.      */  
  25.     @Autowired  
  26.     protected SessionFactory sessionFactory;  
  27.   
  28.     /** 
  29.      * gerCurrentSession 会自动关闭session,使用的是当前的session事务 
  30.      *  
  31.      * @return 
  32.      */  
  33.     public Session getSession() {  
  34.         return sessionFactory.getCurrentSession();  
  35.     }  
  36.   
  37.     /** 
  38.      * openSession 需要手动关闭session 意思是打开一个新的session 
  39.      *  
  40.      * @return 
  41.      */  
  42.     public Session getNewSession() {  
  43.         return sessionFactory.openSession();  
  44.     }  
  45.   
  46.     public void flush() {  
  47.         getSession().flush();  
  48.     }  
  49.   
  50.     public void clear() {  
  51.         getSession().clear();  
  52.     }  
  53.   
  54.     /** 
  55.      * 根据 id 查询信息 
  56.      *  
  57.      * @param id 
  58.      * @return 
  59.      */  
  60.     @SuppressWarnings("rawtypes")  
  61.     public Object load(Class c, String id) {  
  62.         Session session = getSession();  
  63.         return session.get(c, id);  
  64.     }  
  65.   
  66.     /** 
  67.      * 获取所有信息 
  68.      *  
  69.      * @param c  
  70.      *         
  71.      * @return 
  72.      */  
  73.     @SuppressWarnings({ "rawtypes" })  
  74.     public List getAllList(Class c) {  
  75.         String hql = "from " + c.getName();  
  76.         Session session = getSession();  
  77.         return session.createQuery(hql).list();  
  78.     }  
  79.   
  80.     /** 
  81.      * 获取总数量 
  82.      *  
  83.      * @param c 
  84.      * @return 
  85.      */  
  86.     @SuppressWarnings("rawtypes")  
  87.     public Long getTotalCount(Class c) {  
  88.         Session session = getNewSession();  
  89.         String hql = "select count(*) from " + c.getName();  
  90.         Long count = (Long) session.createQuery(hql).uniqueResult();  
  91.         session.close();  
  92.         return count != null ? count.longValue() : 0;  
  93.     }  
  94.   
  95.     /** 
  96.      * 保存 
  97.      *  
  98.      * @param bean  
  99.      *             
  100.      */  
  101.     public void save(Object bean) {  
  102.         try {  
  103.             Session session = getNewSession();  
  104.             session.save(bean);  
  105.             session.flush();  
  106.             session.clear();  
  107.             session.close();  
  108.         } catch (Exception e) {  
  109.             e.printStackTrace();  
  110.         }  
  111.     }  
  112.   
  113.     /** 
  114.      * 更新 
  115.      *  
  116.      * @param bean  
  117.      *             
  118.      */  
  119.     public void update(Object bean) {  
  120.         Session session = getNewSession();  
  121.         session.update(bean);  
  122.         session.flush();  
  123.         session.clear();  
  124.         session.close();  
  125.     }  
  126.   
  127.     /** 
  128.      * 删除 
  129.      *  
  130.      * @param bean  
  131.      *             
  132.      */  
  133.     public void delete(Object bean) {  
  134.         Session session = getNewSession();  
  135.         session.delete(bean);  
  136.         session.flush();  
  137.         session.clear();  
  138.         session.close();  
  139.     }  
  140.   
  141.     /** 
  142.      * 根据ID删除 
  143.      *  
  144.      * @param c 类 
  145.      *             
  146.      * @param id ID 
  147.      *             
  148.      */  
  149.     @SuppressWarnings({ "rawtypes" })  
  150.     public void delete(Class c, String id) {  
  151.         Session session = getNewSession();  
  152.         Object obj = session.get(c, id);  
  153.         session.delete(obj);  
  154.         flush();  
  155.         clear();  
  156.     }  
  157.   
  158.     /** 
  159.      * 批量删除 
  160.      *  
  161.      * @param c 类 
  162.      *             
  163.      * @param ids ID 集合 
  164.      *             
  165.      */  
  166.     @SuppressWarnings({ "rawtypes" })  
  167.     public void delete(Class c, String[] ids) {  
  168.         for (String id : ids) {  
  169.             Object obj = getSession().get(c, id);  
  170.             if (obj != null) {  
  171.                 getSession().delete(obj);  
  172.             }  
  173.         }  
  174.     }  
  175.   
  176. }  

 

 

不知大家有没有注意 applicationContext.xml 这样一句代码

Xml代码   收藏代码
  1. <!-- 设置自动创建|更新|验证数据库表结构 -->  
  2.     hibernate.hbm2ddl.auto=update  

 这个意思是 只要在实体bean指定了entity,那么在数据库会自动创建对应的表和表结构

 

 

test用的一个实体bean

Java代码   收藏代码
  1. package tdxy.bean;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. import javax.persistence.Entity;  
  6. import javax.persistence.Id;  
  7.   
  8. /** 
  9.  *  
  10.  * @ClassName: UserInfoBean 
  11.  * @Description: TODO(用户信息类) 
  12.  * @author dapeng 
  13.  * @date 2014年5月7日 上午12:13:44 
  14.  * @version V1.0 
  15.  *  
  16.  */  
  17. @Entity  
  18. public class UserInfoBean implements Serializable {  
  19.   
  20.     private static final long serialVersionUID = 7280747949998651159L;  
  21.   
  22.     @Id  
  23.     private String id;  
  24.     /** 
  25.      * 昵称 
  26.      */  
  27.     private String nickName;  
  28.     private String pwd;  
  29.     /** 
  30.      * 等级 
  31.      *  
  32.      */  
  33.     private String level;  
  34.   
  35.     /** 
  36.      * 经验值 
  37.      */  
  38.     private String emValue;  
  39.     /** 
  40.      * 性别(0 男 1女) 
  41.      */  
  42.     private String sex;  
  43.     private String birthday;  
  44.     private String qq;  
  45.     private String email;  
  46.     /** 
  47.      * 头像 
  48.      */  
  49.     private String img;  
  50.     /** 
  51.      * 所在地 
  52.      */  
  53.     private String address;  
  54.     /** 
  55.      * 签名 
  56.      */  
  57.     private String qmd;  
  58.   
  59.     public String getId() {  
  60.         return id;  
  61.     }  
  62.   
  63.     public void setId(String id) {  
  64.         this.id = id;  
  65.     }  
  66.   
  67.     public String getNickName() {  
  68.         return nickName;  
  69.     }  
  70.   
  71.     public void setNickName(String nickName) {  
  72.         this.nickName = nickName;  
  73.     }  
  74.   
  75.     public String getPwd() {  
  76.         return pwd;  
  77.     }  
  78.   
  79.     public void setPwd(String pwd) {  
  80.         this.pwd = pwd;  
  81.     }  
  82.   
  83.     public String getLevel() {  
  84.         return level;  
  85.     }  
  86.   
  87.     public void setLevel(String level) {  
  88.         this.level = level;  
  89.     }  
  90.   
  91.     public String getEmValue() {  
  92.         return emValue;  
  93.     }  
  94.   
  95.     public void setEmValue(String emValue) {  
  96.         this.emValue = emValue;  
  97.     }  
  98.   
  99.     public String getSex() {  
  100.         return sex;  
  101.     }  
  102.   
  103.     public void setSex(String sex) {  
  104.         this.sex = sex;  
  105.     }  
  106.   
  107.     public String getBirthday() {  
  108.         return birthday;  
  109.     }  
  110.   
  111.     public void setBirthday(String birthday) {  
  112.         this.birthday = birthday;  
  113.     }  
  114.   
  115.     public String getQq() {  
  116.         return qq;  
  117.     }  
  118.   
  119.     public void setQq(String qq) {  
  120.         this.qq = qq;  
  121.     }  
  122.   
  123.     public String getEmail() {  
  124.         return email;  
  125.     }  
  126.   
  127.     public void setEmail(String email) {  
  128.         this.email = email;  
  129.     }  
  130.   
  131.     public String getImg() {  
  132.         return img;  
  133.     }  
  134.   
  135.     public void setImg(String img) {  
  136.         this.img = img;  
  137.     }  
  138.   
  139.     public String getAddress() {  
  140.         return address;  
  141.     }  
  142.   
  143.     public void setAddress(String address) {  
  144.         this.address = address;  
  145.     }  
  146.   
  147.     public String getQmd() {  
  148.         return qmd;  
  149.     }  
  150.   
  151.     public void setQmd(String qmd) {  
  152.         this.qmd = qmd;  
  153.     }  
  154.   
  155. }  

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

 

以下是test的Service

Java代码   收藏代码
  1. package tdxy.user.service;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.stereotype.Service;  
  5.   
  6. import tdxy.bean.UserInfoBean;  
  7. import tdxy.dao.BaseDao;  
  8. import tdxy.util.TdxyUtil;  
  9.   
  10. @Service  
  11. public class UserInfoService {  
  12.   
  13.     @Autowired  
  14.     private BaseDao baseDao;  
  15.   
  16.     public UserInfoBean queryUserInfoById(String id) {  
  17.         return (UserInfoBean) baseDao.load(UserInfoBean.class, id);  
  18.     }  
  19.   
  20.     public void addUserInfo(UserInfoBean userInfo) {  
  21.         try {  
  22.             userInfo.setId(TdxyUtil.getId());  
  23.             userInfo.setAddress("32132");  
  24.             baseDao.save(userInfo);  
  25.         } catch (Exception e) {  
  26.             e.printStackTrace();  
  27.         }  
  28.     }  
  29. }  

 

 

配置过程到此结束,希望大家一起讨论共同进步。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值