Mybatis与Spring整合(六)

(一)整合环境搭建

1.准备所需要的jar包如以下图所示

这里写图片描述这里写图片描述这里写图片描述

(二)Mybatis与Spring整合方式一:使用传统DAO方式整合

这里写图片描述

项目结构:
这里写图片描述这里写图片描述

实现Mybatis与Spring整合的具体步骤如下:

1.编写配置文件

db.properties配置如下:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root
jdbc.maxTotal=30
jdbc.maxIdle=10
jdbc.initialSize=5

log4j.properties配置如下:

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.itheima=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

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-4.3.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
    <!--读取db.properties -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 开启扫描用于注解方式--> 
    <!-- <context:component-scan base-package="com.itheima.service" />--> 

    <!-- 配置数据源 -->
    <bean id="dataSource" 
            class="org.apache.commons.dbcp2.BasicDataSource">
        <!--数据库驱动 -->
        <property name="driverClassName" value="${jdbc.driver}" />
        <!--连接数据库的url -->
        <property name="url" value="${jdbc.url}" />
        <!--连接数据库的用户名 -->
        <property name="username" value="${jdbc.username}" />
        <!--连接数据库的密码 -->
        <property name="password" value="${jdbc.password}" />
        <!--最大连接数 -->
        <property name="maxTotal" value="${jdbc.maxTotal}" />
        <!--最大空闲连接  -->
        <property name="maxIdle" value="${jdbc.maxIdle}" />
        <!--初始化连接数  -->
        <property name="initialSize" value="${jdbc.initialSize}" />
    </bean>
    <!-- 事务管理器,依赖于数据源 --> 
    <bean id="transactionManager" class=
     "org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean> 
    <!--开启事务注解 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <!--配置MyBatis工厂 -->
    <bean id="sqlSessionFactory" 
            class="org.mybatis.spring.SqlSessionFactoryBean">
         <!--注入数据源 -->
         <property name="dataSource" ref="dataSource" />
         <!--指定核心配置文件位置 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
   </bean>

    <!--实例化CustomerDaoImp -->
    <bean id="customerDao" class="com.wang.Dao.CustomerDaoImp">
    <!-- 注入SqlSessionFactory对象实例-->
         <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>

     <!--实例化CustomerService -->
    <bean id="customerService" class="com.wang.service.CustomerService">
       <property name="customerdao" ref="customerDao"/>
    </bean>
</beans>

mybatis-config.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>
    <!--配置别名 -->
    <typeAliases>
        <package name="com.wang.po" />
    </typeAliases>

    <!--配置Mapper的位置 -->
    <mappers> 
       <mapper resource="com/wang/mapper/CustomerMapper.xml" />
    </mappers>
</configuration>
2.在com.wang.po包下创建Customer.java
package com.wang.po;
//用于封装查询数据
public class Customer {
    private int id;
    private String username;
    private String jobs;
    private String phone;
    ---省略setter和getter方法---
    @Override
    public String toString() {
        return "Customer [id=" + id + ", username=" + username + ", 
        jobs=" + jobs + ", phone=" + phone + "]";
    }

}
3.在com.wang.mapper包下创建CustomerMapper.xml用于配置SQL
<?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.wang.mapper.CustomerMapper">
    <select id="findCustomerById" parameterType="Integer"
        resultType="customer">
        select*from t_customer where id=#{id}
    </select>
</mapper>
4.在com.wang.Dao包下创建CustomerDao.java和CustomerDaoImp.java

CustomerDao.java

package com.wang.Dao;
import com.wang.po.Customer;
public interface CustomerDao {
    //实现按id查询
    public Customer findCustomerById(Integer id);
}

CustomerDaoImp.java

package com.wang.Dao;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import com.wang.po.Customer;
//实现SqlSessionDaoSupport接口,配置Bean时需要setter设值sqlSessionFactory
public class CustomerDaoImp extends SqlSessionDaoSupport
    implements CustomerDao {

    //实现按id查询
    public Customer findCustomerById(Integer id) {
        return this.getSqlSession().selectOne("com.wang.mapper"
                + ".CustomerMapper.findCustomerById", 1);
        }
}
5.在com.wang.service包下创建CustomerService.java
package com.wang.service;
import com.wang.Dao.CustomerDao;
import com.wang.po.Customer;
public class CustomerService {
    private CustomerDao customerdao;

    // setter设值注入
    public void setCustomerdao(CustomerDao customerdao) {
        this.customerdao = customerdao;
    }

    public Customer findCustomerById(Integer id) {
        return this.customerdao.findCustomerById(id);

    }
}
6.在com.wang.MybatisTest包下创建MybatisTest.java测试
package com.wang.MybatisTest;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.wang.po.Customer;
import com.wang.service.CustomerService;
public class MybatisTest {

    @Test
    public void findCustomerById() {
        @SuppressWarnings("resource")
        ApplicationContext con=
            new ClassPathXmlApplicationContext("applicationContext.xml");

        CustomerService customerService=(CustomerService)     
        con.getBean("customerService");
        Customer customer=customerService.findCustomerById(1);
        System.out.println(customer);
    }
}
7.结果输出
Customer [id=1, username=张三, jobs=学生, phone=183999999]

猜你喜欢

转载自blog.csdn.net/weixin_36279318/article/details/80072041