25
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.ContextLoaderListen er</listener-class> </listener> 关关关关 applicationContext.xml 关关 src 关 关关 。,

Spring4.x + hibernate4.x_配置详解

  • Upload
    zanyhui

  • View
    373

  • Download
    3

Embed Size (px)

Citation preview

Page 1: 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"

Page 2: Spring4.x + hibernate4.x_配置详解

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>

Page 3: Spring4.x + hibernate4.x_配置详解

<!-- 配置 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

Page 4: Spring4.x + hibernate4.x_配置详解

<!-- 指定 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"/>

Page 5: Spring4.x + hibernate4.x_配置详解

<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.*(..))" />

Page 6: Spring4.x + hibernate4.x_配置详解

<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" /> </aop:config> </beans>

 

 

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

12345

########################数据库连接信息#############jdbc.username = rootjdbc.password = adminjdbc.url = jdbc:mysql://localhost:3306/tdxy?useUnicode=true&characterEncoding=UTF-8jdbc.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

Page 7: Spring4.x + hibernate4.x_配置详解

* @version V1.0 */@Repositorypublic 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(); }

/**

Page 8: Spring4.x + hibernate4.x_配置详解

* 根据 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; }

/**

Page 9: Spring4.x + hibernate4.x_配置详解

* 保存 * * @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();

Page 10: Spring4.x + hibernate4.x_配置详解

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); } } }

Page 11: Spring4.x + hibernate4.x_配置详解

}

 

 

不知大家有没有注意 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 * */@Entitypublic class UserInfoBean implements Serializable {

private static final long serialVersionUID = 7280747949998651159L;

@Id private String id;

Page 12: Spring4.x + hibernate4.x_配置详解

/** * 昵称 */ 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;

Page 13: Spring4.x + hibernate4.x_配置详解

}

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;

Page 14: Spring4.x + hibernate4.x_配置详解

}

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;

Page 15: Spring4.x + hibernate4.x_配置详解

}

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;

@Servicepublic 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();

Page 16: Spring4.x + hibernate4.x_配置详解

} }}