SSM整合【part3】Spring整合Mybatis

导读:本篇文章讲解 SSM整合【part3】Spring整合Mybatis,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

SSM整合 part3

1. 搭建MyBatis的环境

1.1 在resources中创建SqlMapConfifig.xml配置文件,加入相关xml-dtd约束。

<?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></configuration>

1.2 编写核心配置文件。

<configuration>
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ssmdb?
                                            useSSL=false&amp;serverTimezone=Hongkong&amp;characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

1.3 配置加载映射文件。

<configuration>
    
    <environments>
        <!-- 如1.2配置,略 -->
    </environments>

    <mappers>
        <package name="com.swz"/>
    </mappers>
    
</configuration>

1.4 在AccountDao接口的方法上添加注解,编写SQL语句(不需要 AccountDaoImpl了 )。

public interface AccountDao {

    @Insert("insert into account (name,money) values (#{name},#{money})")
    public void saveAccount(Account account);

    @Select("select * from account")
    public List<Account> findAll();
    
}

2. 单元测试

编写测试两个持久层的方法。

	@Test
    public void testSelect() throws Exception {
        InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        SqlSession session = factory.openSession();

        AccountDao dao = session.getMapper(AccountDao.class);
        List<Account> accounts = dao.findAll();
        for (Account account : accounts) {
            System.out.println(account);
        }

        session.close();
        is.close();
    }

    @Test
    public void testInsert() throws Exception{
        InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        SqlSession session = factory.openSession();
        AccountDao dao = session.getMapper(AccountDao.class);

        Account account = new Account();
        account.setName("玛法里奥·怒风");
        account.setMoney(500d);
        dao.saveAccount(account);

        session.commit();
        session.close();
        is.close();
    }

3. Spring整合MyBatis框架

目的:把SqlMapConfifig.xml配置文件中的内容配置到applicationContext.xml配置文件中。

思路:可直接在spring的applicationContext.xml中配置SqlMapConfifig.xml的有关内容,因此SqlMapConfifig.xml可以直接删了。

3.1 配置C3P0的连接池对象。

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/ssmdb?
                                useSSL=false&amp;serverTimezone=Hongkong&amp;characterEncoding=utf-8"/>
    <property name="username" value="root"/>
    <property name="password" value="123456"/>
</bean>

3.2 配置SqlSession的工厂。(这个类是 org.mabatis.spring 包下的)

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	<property name="dataSource" ref="dataSource"/>
</bean>

3.3 配置扫描dao的包。

<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	<property name="basePackage" value="com.swz"/>
</bean>

3.4 在AccountDao接口中添加@Repository注解(不需要 AccountDaoImpl了 )。

@Repository
public interface AccountDao {
    //1.4介绍过,略
}

3.5 在service中注入dao对象。

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;
    
    //part1介绍过,略
}

3.6 编写Controller测试方法。

@Controller
@RequestMapping("account")
public class AccountController {

    @Autowired
    private AccountService accoutService;

    @RequestMapping("findAll")
    public String testFindAll(Model model){
        List<Account> accounts = accoutService.findAll();
        model.addAttribute("accounts",accounts);
        return "success";
    }

}

编写jsp文件,并开启tomcat服务器进行测试。

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>跳转成功</h3>
    <c:forEach items="${accounts}" var="account">
        ${account.name}:${account.money}
        <br>
    </c:forEach>
</body>
</html>

4. 配置 spring 的声明式事务管理

4.1 在applicationContext.xml中配置事务管理器。

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

4.2 配置事务的通知。

<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
        <tx:method name="*" read-only="false" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>

4.3 配置 aop,并配置切入点表达式和建立通知和切入点表达式的关系。

<aop:config>
    <aop:pointcut id="pt1" expression="execution(* com.swz.service.impl.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>

4.4 测试事务的整合结果。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class testMain {

    @Autowired
    private AccountService accountService;

    @Test
    public void testFindAll() {
        List<Account> accounts = accountService.findAll();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("玛法里奥·怒风");
        account.setMoney(1800d);
        accountService.saveAccount(account);
    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/84483.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!