Spring事务管理-零配置版

一、拷贝必要的jar包到工程的lib目录

二、准备数据库表和实体类

创建数据库:
create database spring;
use spring;
创建表:
create table account(
    id int primary key auto_increment,
    name varchar(40),
    money float
)character set utf8 collate utf8_general_ci;
package com.yiidian.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
 * @author http://www.yiidian.com
 * 
 */
@Entity
@Table(name="account")
public class Account implements Serializable{
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name="id")
	private Integer id;
	@Column(name="name")
	private String name;
	@Column(name="money")
	private Float money;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Float getMoney() {
		return money;
	}
	public void setMoney(Float money) {
		this.money = money;
	}
	@Override
	public String toString() {
		return "Account [id=" + id + ", name=" + name + ", money=" + money
				+ "]";
	}

	
}

注意:该类使用JPA注解形式


三、编写业务层接口和实现类

AccountService:

package com.yiidian.service;

import com.yiidian.domain.Account;
/**
 * @author http://www.yiidian.com
 * 
 */
public interface AccountService {
	/**
	 * 根据id查询账户信息
	 * @param id
	 * @return
	 */
	Account findAccountById(Integer id);//查
	
	/**
	 * 转账
	 * @param sourceName	转出账户名称
	 * @param targeName		转入账户名称
	 * @param money			转账金额
	 */
	void transfer(String sourceName,String targeName,Float money);//增删改
}

AccountServiceImpl:

package com.yiidian.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yiidian.dao.AccountDao;
import com.yiidian.domain.Account;
import com.yiidian.service.AccountService;
/**
 * @author http://www.yiidian.com
 * 
 */
@Service("accountService")
@Transactional
public class AccountServiceImpl implements AccountService {
	@Resource
	private AccountDao accountDao;

	@Override
	public Account findAccountById(Integer id) {
		return accountDao.findAccountById(id);
	}

	@Override
	public void transfer(String sourceName, String targeName, Float money) {
		// 1.根据名称查询两个账户
		Account source = accountDao.findAccountByName(sourceName);
		Account target = accountDao.findAccountByName(targeName);
		// 2.修改两个账户的金额
		source.setMoney(source.getMoney() - money);// 转出账户减钱
		target.setMoney(target.getMoney() + money);// 转入账户加钱
		// 3.更新两个账户
		accountDao.updateAccount(source);
		//模拟异常
		//int i = 1 / 0;
		accountDao.updateAccount(target);
	}
}

四、编写Dao接口和实现类

AccountDao:

package com.yiidian.dao;

import com.yiidian.domain.Account;

/**
 * 
 * @author http://www.yiidian.com
 * 
 */
public interface AccountDao {

	/**
	 * 根据id查询账户信息
	 * @param id
	 * @return
	 */
	Account findAccountById(Integer id);

	/**
	 * 根据名称查询账户信息
	 * @return
	 */
	Account findAccountByName(String name);
	
	/**
	 * 更新账户信息
	 * @param account
	 */
	void updateAccount(Account account);
}

AccountDaoImpl:

package com.yiidian.dao.impl;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.yiidian.dao.AccountDao;
import com.yiidian.domain.Account;
/**
 * 
 * @author http://www.yiidian.com
 * 
 */
@Repository("accountDao")
public class AccountDaoImpl extends HibernateDaoSupport  implements AccountDao{
	
	@Resource
	public void setMySessiionFactory(SessionFactory sessionFactory){
		super.setSessionFactory(sessionFactory);
	}
	
	@Override
	public Account findAccountById(Integer id) {
		return this.getHibernateTemplate().get(Account.class, id);
	}

	@Override
	public Account findAccountByName(String name) {
		return (Account) this.getHibernateTemplate().find("from Account where name = ?", name).get(0);
	}

	@Override
	public void updateAccount(Account account) {
		this.getHibernateTemplate().update(account);
	}
}

五、编写Spring配置类

JdbcConfig:

package com.yiidian.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
 * 
 * @author http://www.yiidian.com
 * 
 */
@PropertySource(value="classpath:jdbc.properties")
@EnableTransactionManagement  //开启Spring注解事务
public class JdbcConfig {
	@Value("${jdbc.driverClass}")
	private String driverClass;
	@Value("${jdbc.url}")
	private String url;
	@Value("${jdbc.username}")
	private String username;
	@Value("${jdbc.password}")
	private String password;
	

	@Bean(name="dataSource")
	public DataSource getDataSource(){
		DriverManagerDataSource ds = new DriverManagerDataSource();
		ds.setDriverClassName(driverClass);
		ds.setUrl(url);
		ds.setUsername(username);
		ds.setPassword(password);
		return ds;
	}
	
	@Bean(name="sessionFactory")
	public LocalSessionFactoryBean getJdbcTemplate(@Qualifier("dataSource")DataSource ds){
		LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
		factory.setDataSource(ds);
		Properties props = new Properties();
		props.setProperty("hibernate.shql_sql", "true");
		props.setProperty("hibernate.format_sql", "true");
		props.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
		factory.setPackagesToScan("com.yiidian.domain");
		factory.setHibernateProperties(props);
		return factory;
	}
	
	@Bean(name="transactionManager")
	public HibernateTransactionManager getDataSourceTransactionManager(@Qualifier("sessionFactory")SessionFactory sessionFactory){
		HibernateTransactionManager manager = new HibernateTransactionManager();
		manager.setSessionFactory(sessionFactory);
		return manager;
	}
}

SpringConfig:

package com.yiidian.config;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * Spring配置类
 * @author http://www.yiidian.com
 *
 */
@Configurable
@ComponentScan(basePackages="com.yiidian") //扫描注解类
@Import(value=JdbcConfig.class)  //导入其他配置类
public class SpringConfig {

}

六、编写测试类

package com.yiidian.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.yiidian.service.AccountService;
/**
 * @author http://www.yiidian.com
 *
 */
public class HibernateTemplateDemo {
	@Test
	public void test1() {
		ApplicationContext ac = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		AccountService accountService = (AccountService)ac.getBean("accountService");
		accountService.transfer("小苍", "小泽", 300f);
	}
}

 

源码下载:http://pan.baidu.com/s/1bpJG5l1

热门文章

优秀文章