Spring_MyBatis整合(基于注解方式)
先导包
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
再写数据库连接配置类
public class JdbcConfig {
@Bean//将DataSource注入Spring 容器中
public DataSource getDataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///test?useUnicode=true&characterEncoding=utf-8");
dataSource.setUsername("root");
dataSource.setPassword("200429@wbnb");
return dataSource;
}
@Bean//将SqlSessionFactoryBean注入到Spring容器中
public SqlSessionFactoryBean create(DataSource dataSource){
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
Resource resource = new ClassPathResource("SqlMapConfig.xml");
sqlSessionFactoryBean.setConfigLocation(resource);
return sqlSessionFactoryBean;
}
}
创建实体类
public class Account {
private int id;
private String name;
private double money;
}
tx
public class TransactionConfig {
@Bean
public PlatformTransactionManager createTransactionConfig(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}
@Configuration
@ComponentScan(basePackages = "com.wdzl")
@Import(value = {JdbcConfig.class, TransactionConfig.class})
@EnableTransactionManagement
public class SpringConfig {
}
创建dao
public interface AccountDao {
/**
* 根据用户名查询用户信息
* @param name
* @return
*/
@Select("select * from account where name=#{name}")
Account findAccountByName(String name);
/**
* 更新用户信息
* @param account
*/
@Update("update account set name=#{name},money=#{money} where id=#{id}")
void updateAccount(Account account);
}
@Repository
public class AccountDaoImpl implements AccountDao {
//注入SqlSession工厂
@Autowired
private SqlSessionFactory sqlSessionFactory;
@Override
public Account findAccountByName(String name) {
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
return accountDao.findAccountByName(name);
}
@Override
public void updateAccount(Account account) {
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
accountDao.updateAccount(account);
}
}
service
public interface AccountService {
/**
*
* @param sourceName 转出姓名
* @param targetName 转入姓名
* @param money 转账金额
*/
void transfer(String sourceName,String targetName,double money);
}
@Service
public class AccountServiceImpl implements AccountService {
//注入数据访问层
@Autowired
private AccountDao accountDao;
@Override
public void transfer(String sourceName, String targetName, double money) {
//查询转出账户对象
Account source = accountDao.findAccountByName(sourceName);
//查询转入账户对象
Account target = accountDao.findAccountByName(targetName);
//按段是否存在账户
if (source!=null&&target!=null){
//设置转入金额
source.setMoney(source.getMoney()-money);
target.setMoney(target.getMoney()+money);
//更新账户
accountDao.updateAccount(source);
accountDao.updateAccount(target);
}
}
}
contorller
@Controller
public class AccountController {
@Autowired
private AccountService accountService;
public void transfer(String sourceName,String targetName,double money){
try{
accountService.transfer(sourceName,targetName,money);
System.out.println("转账成功");
}catch (Exception e){
System.out.println("转账失败");
}
}
}
test
public class AccountTest {
@Test
public void test(){
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
AccountController accountController = context.getBean("accountController", AccountController.class);
accountController.transfer("aa","bb",500.00);
}
}
Spring_MyBatis整合(基于XML方式)
准备工作
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wdzl</groupId>
<artifactId>Spring_Xml</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<!-- aop增强处理,支持切入点表达式-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<!-- 声明式事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<!-- 引入MyBatis与spring的整合包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
1.首先在Dao层下创建两个接口
package com.wdzl.dao;
import com.wdzl.pojo.Account;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
public interface IAccountDao {
/**
* 根据账户名称查询账户对象
* @param name
* @return
*/
@Select("select * from account where name=#{name}")
Account findAccountByName(String name);
/**
* 更新账户信息
* @param account
*/
@Update("update account set name=#{name},money=#{money} where id=#{id}")
void updateAccount(Account account);
}
package com.wdzl.dao;
public interface AccountDao {
}
2.在Dao层下创建新的包impl下创建AccountDaoImpl
package com.wdzl.dao.impl;
import com.wdzl.dao.IAccountDao;
import com.wdzl.pojo.Account;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
/**
* 持久层实现类
*/
public class AccountDaoImpl extends SqlSessionDaoSupport implements IAccountDao {
/**
* 查询账户信息
* @param name
* @return
*/
@Override
public Account findAccountByName(String name) {
//获取session
SqlSession session = super.getSqlSession();
IAccountDao mapper = session.getMapper(IAccountDao.class);
Account account = mapper.findAccountByName(name);
//释放资源
return account;
}
/**
* 更新账户信息
* @param account
*/
@Override
public void updateAccount(Account account) {
SqlSession session = super.getSqlSession();
IAccountDao mapper = session.getMapper(IAccountDao.class);
mapper.updateAccount(account);
}
}
3.创建实体类
package com.wdzl.pojo;
public class Account {
private Integer id;
private String name;
private double 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 double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
4.在biz层创建一个IAccountBiz接口和impl下的AccountBizImpl类
package com.wdzl.biz;
public interface IAccountBiz {
/**
* 转账⽅法
* @param sourceName 转出账户名称
* @param targetName 转⼊账户名称
* @param money 转账⾦额
*/
void transfer(String sourceName,String targetName,double money);
void testLog();
}
package com.wdzl.biz.impl;
import com.wdzl.biz.IAccountBiz;
import com.wdzl.dao.IAccountDao;
import com.wdzl.pojo.Account;
public class AccountBizImpl implements IAccountBiz {
private IAccountDao accountDao;
@Override
public void transfer(String sourceName, String targetName, double money) {
//转出账户信息
Account source = accountDao.findAccountByName(sourceName);
//转入账户信息
Account target = accountDao.findAccountByName(targetName);
if (source!=null&&target!=null){
source.setMoney(source.getMoney()-money);
target.setMoney(target.getMoney()+money);
accountDao.updateAccount(source);
accountDao.updateAccount(target);
}
}
public void setAccountDao(IAccountDao accountDao){
this.accountDao=accountDao;
}
public IAccountDao getAccountDao(){
return accountDao;
}
@Override
public void testLog() {
System.out.println("测试日志增强处理有没有加入");
}
}
5.日志类
package com.wdzl.log;
public class Logger {
public void before(){
System.out.println("前置增强处理内容被植入");
}
public void after(){
System.out.println("最终增强(有无异常均处理)处理内容被植入");
}
public void afterReturning(){
System.out.println("后置增强(⽆异常情况)处理内容被植⼊......");
}
public void afterThrowing(){
System.out.println("异常增强处理内容被植⼊......");
}
}
6.注入业务逻辑层Controller
package com.wdzl.controller;
import com.wdzl.biz.IAccountBiz;
public class AccountController {
//注⼊业务逻辑层
private IAccountBiz accountBiz;
//转账
public void transfer(String sourceName,String targetName,double money){
//调⽤业务层中转账的⽅法
accountBiz.transfer(sourceName,targetName,money);
System.out.println("转账成功!");
}
public void setAccountBiz(IAccountBiz accountBiz) {
this.accountBiz = accountBiz;
}
public IAccountBiz getAccountBiz() {
return accountBiz;
}
}
构建resource
- Bean-log.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="logger" class="com.wdzl.log.Logger"></bean>
<bean id="accountBiz" class="com.wdzl.biz.impl.AccountBizImpl"></bean>
<aop:config>
<aop:pointcut id="mypointcut" expression="execution(* com.wdzl.biz.impl.*.*(..))"/>
<aop:aspect id="logAdvice" ref="logger">
<aop:before method="before" pointcut-ref="mypointcut"></aop:before>
<aop:after method="after" pointcut-ref="mypointcut"></aop:after>
<aop:after-returning method="afterReturning" pointcut-ref="mypointcut"></aop:after-returning>
<aop:after-throwing method="afterThrowing" pointcut-ref="mypointcut"></aop:after-throwing>
</aop:aspect>
</aop:config>
</beans>
2.bean-tx.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 引入db.properties文件-->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!--引入数据访问层实现类 -->
<bean id="accountDao" class="com.wdzl.dao.impl.AccountDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<!--注入业务逻辑层-->
<bean id="accountBiz" class="com.wdzl.biz.impl.AccountBizImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 注入控制层-->
<bean id="accountController" class="com.wdzl.controller.AccountController">
<property name="accountBiz" ref="accountBiz"></property>
</bean>
<!-- 引入控制层-->
<bean id="accountConotroller" class="com.wdzl.controller.AccountController">
<property name="accountBiz" ref="accountBiz"></property>
</bean>
<!-- 注入数据源-->
<bean id="datasource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 注入sqlsession-->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"></property>
<property name="configLocation" value="classpath:SqlMapConfig.xml">
</property>
</bean>
<!-- 注入Spring声明式事务对象-->
<bean id="dataSourceTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"></property>
</bean>
<!-- 配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
<!-- 配置事务的属性-->
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
</tx:attributes>
</tx:advice>
<!-- aop设置-->
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.wdzl.biz.impl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"></aop:advisor>
</aop:config>
</beans>
3.db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///test?useSSL=false
jdbc.username=........
jdbc.password=........
4.主配置文件SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<mappers>
<mapper class="com.wdzl.dao.IAccountDao"></mapper>
</mappers>
</configuration>
test
1.AccountControllertest
import com.wdzl.biz.IAccountBiz;
import com.wdzl.controller.AccountController;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AccountControlertest {
private ApplicationContext context;
@Before
public void springinit(){
context = new ClassPathXmlApplicationContext("bean-tx.xml");
}
@Test
public void testTransfer(){
AccountController accountController =
context.getBean("accountController", AccountController.class);
accountController.transfer("aa","bb",200.00);
}
@Test
public void test(){
IAccountBiz accountBiz = context.getBean("accountBiz",
IAccountBiz.class);
accountBiz.testLog();
}
}
2.LoggerTest
import com.wdzl.biz.IAccountBiz;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class LoggerTest {
private ApplicationContext context;
@Before
public void springinit(){
context = new ClassPathXmlApplicationContext("bean-log.xml");
}
@Test
public void testLog(){
IAccountBiz accountBiz = context.getBean("accountBiz",
IAccountBiz.class);
accountBiz.testLog();
}
}
总结
- 两种方式实现的是一种功能,后可以根据自己的习惯,具体的需要合理的运用
og();
}
}
2.LoggerTest
```java
import com.wdzl.biz.IAccountBiz;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class LoggerTest {
private ApplicationContext context;
@Before
public void springinit(){
context = new ClassPathXmlApplicationContext("bean-log.xml");
}
@Test
public void testLog(){
IAccountBiz accountBiz = context.getBean("accountBiz",
IAccountBiz.class);
accountBiz.testLog();
}
}
总结
- 两种方式实现的是一种功能,后可以根据自己的习惯,具体的需要合理的运用
- 我个人在XML方式中也运用了注解方式,因为这样会让代码更加的简介方便,两种方式是可以穿插着使用的,而且我的resourde看起来复杂是因为我引入了日志配置文件,这个有没有都无所谓