Spring集成MyBatis

使用MyBatis,需要创建MyBatis框架中的某些对象,使用这些对象,就能使用mybatis提供的功能了。

  1. 需要有Dao接口的代理对象,例如StudentDao接口,需要一个他的代理对象,使用SqlSession.getMapper(StudentDao.class),得到dao代理对象。
  2. 需要由SqlSessionFactory,创建SqlSessionFactory才能使用openSession得到SqlSession对象。
  3. 在处理大型项目的时候,MyBatis提供的数据源(PooledDataSource)难以满足项目需求,通常会更换一个连接池对象。

Spring容器 (面对Spring开发,从Spring中获得对象)

DataSource对象,数据源

SqlSessionFactory对象

dao接口的代理对象1~n

注:以上对象都由Spring使用IOC创建好对象。

实现步骤:

  1. 使用msyql数据库,使用学生表student(id int 主键列 自动增长,
    name varchar(80) ,
    age int )。
  2. 创建maven项目
  3. 加入依赖:spring依赖,mybatis依赖,mysql驱动,junit依赖,mybatis-spring依赖(mybatis网站上提供的,用来在spring项目中创建mybatis对象),spring事务相关的依赖。
  4. 创建实体类Student
  5. 创建Dao接口和Mapper文件写SQL语句
  6. 写mybatis主配置文件
  7. 创建service接口其实现类
  8. 创建spring的配置文件
  • 声明数据源DataSource,使用阿里的Druid连接池
  • 声明SqlSessionFactoryBeanlei,在这个类内部创建的是SqlSessionFactory对象
  • 声明MapperScannerConfiguration类,在内部创建dao代理对象,创建的对象都放在spring容器中。
  • 声明service对象,将上一步中的dao赋值给service属性,让其进行业务层的操作
  1. 测试dao访问数据库

操作

  1. 自己建表,三个属性(id(主键),name,age)
  2. 创建maven项目(IDEA)
  3. 具体依赖:
  • junit (单元测试)
  • spring-context (spring依赖)
  • spring-tx ,spring-jdbc(spring事务的依赖)
  • mybatis(mybatis依赖)
  • mybatis-spring(mybatis和spring集成的依赖)
  • mysql-connector-java(msyql驱动)
  • druid(阿里连接池)
<!-- resource插件 -->
<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>
  1. 创建实体类
public class Student {
    private Integer id;
    private String name;
    private Integer age;

    public Integer getId() {
        return id;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
  1. 创建Dao接口和mapper文件
public interface StudentDao {

    int insertStudent(Student student);

    List<Student> selectStudents();

}
<!--  -->
<?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.dao.StudentDao">

	<insert id="insertStudent">
		insert into student(name,age) values(#{name},#{age})
	</insert>

	<select id="selectStudents" resultType="com.wang.domain.Student">
		select id,name,age from student
	</select>

</mapper>
  1. 写MyBatis主配置文件
<?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.domain"/>
    </typeAliases>


    <!--MyBatis的SQL语句和映射配置文件,指定其他Mapper文件的位置-->
    <!--    找到相应的sql语句-->
    <mappers>
        <mapper resource="com/wang/dao/StudentDao.xml"/>
    </mappers>
</configuration>
  1. 创建service接口和实现类
public interface StudentService {

    int addStudent(Student student);

    List<Student> queryStudent();

}
public class StudentServiceImpl implements StudentService {

	private StudentDao studentDao;

	public void setStudentDao(StudentDao studentDao){
		this.studentDao = studentDao;
	}

	@Override
	public int addStudent(Student student) {
		int i = studentDao.insertStudent(student);
		return i;
	}

	@Override
	public List<Student> queryStudent() {
		List<Student> students = studentDao.selectStudents();
		return students;
	}
}
  1. 创建spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<!--    声明数据源-->
    <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="jdbc:mysql://localhost:3306/learnjdbc" />
        <property name="username" value="root" />
        <property name="password" value="wang" />
    </bean>

<!--    声明SqlSessionFactoryBean-->
    <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定数据源 -->
        <property name="dataSource" ref="myDataSource"/>

        <!-- 指定MyBatis主配置文件 -->
        <property name="configLocation" value="classpath:MyBatisConfig.xml" />

    </bean>


<!--    声明MapperScannerConfiguration
        SqlSession.getMapper(StudentDao.class);
        MapperScannerConfigurer作用是:
            循环basePackage所表示的包,把保重的每一个接口都找到,调用SqlSession.getMapper()把每个
            dao接口都创建出dao对象,dao代理对象放在容器中。
        -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 指定SqlSessionFactory对象名称 -->
        <property name="sqlSessionFactoryBeanName" value="factory"/>
        <!-- 指定基本包,dao接口所在的包名 -->
        <property name="basePackage" value="com.wang.dao"/>
    </bean>

<!--    声明service-->
    <bean id="studentService" class="com.wang.service.impl.StudentServiceImpl">
        <property name="studentDao" ref="studentDao"/>
    </bean>
</beans>

接下来就可以通过junit进行测试了。

结尾:

  • 该过程中的一部分可以使用注解的方式进行(略)
  • MyBatis通常使用配置文件的方式,spring通常使用注解的方式
  • ssm框架的整合实际上就是MyBatis和spring框架的整合
  • 接下来再添加springMvc后,在控制层调用相应的业务处理层即是service的方法就可以实现ssm框架的运行。