当前位置:文档之家› spring4.x + hibernate4.x 配置详解

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</l istener-class></listener>然后建立 applicationContext.xml 文件,src下。

文件内容如下,注释我尽量写的很详细<beans xmlns:xsi="/2001/XMLSchema-instance"xmlns="/schema/beans"xmlns:aop="http://ww /schema/aop"xmlns:context="/schema/context"xmlns:tx="ht tp:///schema/tx"xmlns:cache="/schema/cache"xmlns:p="http:// /schema/p"xsi:schemaLocation="/schema/beans /schema/beans/spring-beans-4.0.xsd/schema/aop/schema/aop/spring-aop-4.0.xsd/schema/context/schema/context/spring-context-4.0.xsd/schema/tx/schema/tx/spring-tx-4.0.xsd/schema/cache http://www.springframewor /schema/cache/spring-cache-4.0.xsd"><!-- 引入properties文件--><context:property-placeholder location="classpath*:/appConfig.properties"/> <!-- 定义数据库连接池数据源bean destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用--> <bean id="dataSource"class="boPooledDataSourc e"destroy-method="close"><!-- 设置JDBC驱动名称--><property name="driverClass"value="${jdbc.driver}"/><!-- 设置JDBC连接URL --><property name="jdbcUrl"value="${jdbc.url}"/><!-- 设置数据库用户名--><property name="user"value="${ername}"/><!-- 设置数据库密码--><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<!-- 是否开启二级缓存-->e_second_level_cache=false<!-- 是否开启查询缓存-->e_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.or m.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.AutowiredAnnotati onBeanPostProcessor"/><!-- 扫描有注解的文件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"/></beans>自己写了一个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*/@Repositorypublic class BaseDao {/*** Autowired 自动装配相当于get() set()*/@Autowiredprotected 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用的一个实体beanpackage 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**/@Entitypublic class UserInfoBean implements Serializable {private static final long serialVersionUID = 7280747949998651159L;@Idprivate 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是一样的,大家可以自己查看一下即可。

相关主题