搭建和测试 MyBatis 的环境:
编写 AccountMapper.xml 映射配置文件:
XML
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.qcby.mapper.AccountMapper">
<select id="findAll" resultType="com.qcby.domain.Account">
select * from account;
</select>
</mapper>
在 web 项目中编写 SqlMapConfig.xml 的配置文件,编写核心配置文件
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>
<!-- 配置环境 -->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///ssm"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 加载映射配置文件 -->
<mappers>
<mapper resource="mapper/AccountMapper.xml"/>
</mappers>
</configuration>
在 AccountMapper 接口中编写方法:
java
public interface AccountMapper {
public List<Account> findAll();
}
编写测试方法(此时数据库还没有数据):
java
@Test
public void run1() throws IOException {
//加载配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//创建 session
SqlSession session = factory.openSession();
//获取代理对象
AccountMapper accountMapper = session.getMapper(AccountMapper.class);
List<Account> all = accountMapper.findAll();
all.forEach(System.out::println);
//关闭资源
session.close();
in.close();
}
Spring 整合 MyBatis 框架:
目的:
-
把 SqlMapConfig.xml 配置文件中的内容配置到 applicationContext.xml 配置文件中:
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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" 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/context http://www.springframework.org/schema/context/spring-context.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"> <!-- 开启注解扫描,要扫描的是service --> <context:component-scan base-package="com.qcby.service"/> <!-- 配置 druid 连接池 --> <!-- 配置开源连接池 Druid 连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///ssm"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <!-- Spring 框架整合 MyBatis 框架 --> <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入连接池对象 --> <property name="dataSource" ref="dataSource"/> <!-- 加载映射配置文件 --> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!-- 把 mapper 对象存入 IOC 容器中 --> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactory" ref="sessionFactory"/> <property name="basePackage" value="com.qcby.mapper"/> </bean> <!-- 平台事务管理器 --> <bean id="transactionManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置事务的通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManger"> <tx:attributes> <tx:method name="find*" read-only="true"/> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- 配置事务的增强 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(public * com.qcby.service.Impl.*ServiceImpl.*(..))"/> </aop:config> </beans>
在 AccountMapper 接口中添加 @Repository 注解:
在 service 中注入 mapper 对象,进行测试:
-
service 层代码:
java@Service public class AccountServiceImpl implements AccountService { @Autowired private AccountMapper accountMapper; @Override public List<Account> findAll() { System.out.println("业务层逻辑:查询所有账号"); List<Account> list = accountMapper.findAll(); return list; } @Override public void save(Account account) { accountMapper.save(account); } }
-
层代码:
java@Controller @RequestMapping("/account") public class AccountController { @Autowired private AccountService accountService; /** * 查询所有方法 */ @RequestMapping("/findAll") public ModelAndView findAll(){ System.out.println("表现层:查询所有账户"); List<Account> list = accountService.findAll(); for (Account a : list){ System.out.println(a); } ModelAndView mv = new ModelAndView(); mv.setViewName("suc"); return mv; } }
-
配置声明事务管理:
XML<!-- 平台事务管理器 --> <bean id="transactionManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置事务的通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManger"> <tx:attributes> <tx:method name="find*" read-only="true"/> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- 配置事务的增强 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(public * com.qcby.service.Impl.*ServiceImpl.*(..))"/> </aop:config>
-
表单代码:
XML<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <body> <h2>Hello World!</h2> <a href="/account/findAll">查询所有</a> <h3>账号列表页面</h3> <a href="/account/findAll.do">查询所有</a> <h3>测试新增</h3> <form action="/account/save" method="post"> 姓名:<input type="text" name="name" /><br/> 金额:<input type="text" name="money" /><br/> <input type="submit" value="保存" /> </form> </body> </html>
-
controller 代码:
java@Controller @RequestMapping("/account") public class AccountController { @Autowired private AccountService accountService; /** * 查询所有方法 */ @RequestMapping("/findAll") public ModelAndView findAll(){ System.out.println("表现层:查询所有账户"); List<Account> list = accountService.findAll(); for (Account a : list){ System.out.println(a); } ModelAndView mv = new ModelAndView(); mv.setViewName("suc"); return mv; } @RequestMapping("/save") public String save(Account account){ //调用 Service 层保存数据 accountService.save(account); return "suc"; } }
-
service 代码:
java@Service public class AccountServiceImpl implements AccountService { @Autowired private AccountMapper accountMapper; @Override public List<Account> findAll() { System.out.println("业务层逻辑:查询所有账号"); List<Account> list = accountMapper.findAll(); return list; } @Override public void save(Account account) { accountMapper.save(account); } }
-
mapper 代码:
java@Repository public interface AccountMapper { public List<Account> findAll(); @Insert("insert into account (name,money) values (#{name},#{money})") void save(Account account); }