在这篇博客中我直接使用sessionFactory来获得currentSession来操纵数据库,在我上一篇博客中出现的问题,HibernateTemplate在Hibernate4.0中被抛弃了,所以这个方法刚好解决了这个问题。
一、项目的结构图
二、具体实现
1、User类
@Entity
@Table(name="t_user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
@Column(name="username",length=50)
private String username;
@Column(name="password",length=50)
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
2、UserDao接口
public interface UserDao {
public void save(User user);
public void update(User user);
public void delete(User user);
public User findById(Integer id);
public List<User> findAll();
}
3、UserDaoImpl 类
采用事务功能提高代码的安全性,通过spring注释的方式自动加载sessionFactory通过setter方法
@Repository
public class UserDaoImpl implements UserDao{
private SessionFactory sessionFactory;
@Autowired
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory=sessionFactory;
}
public SessionFactory getSessionFactory(){
return this.sessionFactory;
}
public Session getCurrentSession(){
return this.sessionFactory.getCurrentSession();
}
public void save(User user) {
Transaction tx=this.getCurrentSession().beginTransaction();
try{
this.getCurrentSession().save(user);
tx.commit();
}catch(Exception e){
if(null!=tx){tx.rollback();}
e.printStackTrace();
}
}
public void update(User user) {
Transaction tx=this.getCurrentSession().beginTransaction();
try{
this.getCurrentSession().update(user);
tx.commit();
}catch(Exception e){
if(null!=tx){tx.rollback();}
e.printStackTrace();
}
}
public void delete(User user) {
Transaction tx=this.getCurrentSession().beginTransaction();
try{
this.getCurrentSession().delete(user);
tx.commit();
}catch(Exception e){
if(null!=tx){tx.rollback();}
e.printStackTrace();
}
}
public User findById(Integer id) {
Transaction tx=this.getCurrentSession().beginTransaction();
User user=(User)this.getCurrentSession().get(User.class, id);
tx.commit();
return user;
}
public List<User> findAll() {
Transaction tx=this.getCurrentSession().beginTransaction();
List<User> users=(List<User>) this.getCurrentSession().get(User.class,null);
tx.commit();
return users;
}
}
4、applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<!-- 扫描 -->
<context:component-scan base-package="cn.wjw"></context:component-scan>
<!-- 0.1加载properties -->
<context:property-placeholder location="classpath:c3p0-db.properties"/>
<!-- 0.2配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 1.配置 SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- 1.1配置数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 1.2 其他配置项,要使用Hibernate全属性名,如果Hibernate.不要省略 -->
<property name="hibernateProperties">
<props>
<!-- 数据库方言定义 -->
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQL5Dialect
</prop>
<!-- 向控制台显示执行的SQL语句 -->
<prop key="hibernate.show_sql">true</prop>
<!-- 创建SessionFactory对象时自动创建数据库表 -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!-- 取消bean校验 -->
<prop key="javax.persistence.validation.mode">none</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key=""></prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>cn.wjw.domain</value>
</list>
</property>
</bean>
<!-- 4.事务管理 -->
<!-- #1 事务管理器,就是平台,Spring工具产生,依赖于使用 持久方案 (hibernate、jdbc等) -->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 将事务管理注册Spring
* proxy-target-class="true" :使用cglib
* proxy-target-class="false":有接口将使用JDK-->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
5、c3p0-db.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc\:mysql\://localhost\:3306/database?useUnicode\=true&characterEncoding\=utf-8
jdbc.user=你的数据库用户名
jdbc.password=你的数据库密码
6、Spring注释的优点
使得代码简洁,但却可读性降低,但是在平时的开发中熟练这种方法有助于提高开发效率。