今天主要学了spring整合mybatis


创建项目的步骤

  1. 新建maven项目
  2. 加入maven的依赖
    (1)spring依赖
    (2)mybatis依赖
    (3)mysql驱动
    (4)spring事务的依赖
    (5)mybatis和spring集成的依赖:mybatis官方提供的,用来在spring项目中创建mybatis的 SQLSessionFactory,dao对象的
  3. 创建实体类
  4. 创建dao接口mapper文件
  5. 创建mybatis主配置文件
  6. 创建service接口和实现类,属性是dao
  7. 创建spring的配置文件:声明mybatis的对象交给spring创建
    (1)数据库
    (2)SQLSessionFactory
    (3)dao对象
    (4)声明自定义的service
  8. 创建测试类,获取service对象,通过service调用dao完成数据库的访问

maven依赖

<?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.myproject</groupId>
  <artifactId>ch07-spring-mybatis</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>ch07-spring-mybatis</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!--spring核心-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <!--做spring事务用到的-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <!--mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>
    <!--mybatis和spring集成的依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>
    <!--mysql驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.9</version>
    </dependency>
    <!--阿里公司数据连接池-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.12</version>
    </dependency>
  </dependencies>
  <!--依赖-->
  <build>
    <!--目的是把src/main/java目录中的xml文件包含到输出结果中。输出到classes目录中-->
    <resources>
      <resource>
        <directory>src/main/java</directory><!--所在的目录-->
        <includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
    <!--指定jdk版本-->
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>14</source>
          <target>14</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

创建实体类

//这里的getter and setter细节就省略了
public class Student {
    private String name;
    private Integer id;
    private String email;
    private Integer age;
}

创建dao接口的mapper文件

这里我用的是自己建立的模板,大家也可以在设置里面自己创建一个

<?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.myproject.dao.StudentDao">
    <insert id="insertStudent">
        insert into student values(#{id},#{name},#{age},#{email})
    </insert>

    <select id="selectStudent" resultType="com.myproject.domain.Student">
        select * from student order by id
    </select>
</mapper>

创建mybatis主配置文件

这里也用的是模板

<!--日志-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <typeAliases>
        <!--实体类所在的包名-->
        <package name="com.myproject.domain"/>
    </typeAliases>

    <!--sql mapper 映射文件的位置-->
    <mappers>
        <mapper resource="com/myproject/dao/StudentDao.xml"/>
    </mappers>

创建service接口和实现类,属性是dao

ublic interface StudentService {
    int addStudent(Student student);
    List<Student> queryStudents();
}
public class StudentServiceImpl implements StudentService {
    private StudentDao studentDao;

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

//实现类

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

    @Override
    public List<Student> queryStudents() {
        List<Student> students=studentDao.selectStudent();
        return students;
    }
}

创建spring的配置文件:声明mybatis的对象交给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" xmlns:util="http://www.springframework.org/schema/util"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="jdbc.properties"/>
<!--数据源-->
    <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">

        <!--set注入给DruidDataSource提供连接数据库信息-->
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxActive" value="${jdbc.max}"/>
    </bean>

<!--factory-->
    <!--声明的是mybatis中提供的SQLSessionFactoryBean类,这个类内部创建SQLSessionFactory的-->
    <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--set注入,把数据库连接池付给了DataSource属性-->
        <property name="dataSource" ref="myDataSource"/>
        <!--mybatis主配置文件的位置
            configLocation属性是Resource类型,读取配置文件
            赋值使用value,指定文件的路径使用classpath:文件的位置
        -->
        <property name="configLocation" value="classpath:mybatis.xml"/>
    </bean>
    <!--创建dao对象,使用SQLSession的getMapper
    MapperScannerConfigurer:在内部调用getMapper生成每个dao接口的代理对象
    -->

<!--dao-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定SQLSessionFactory的id-->
        <property name="sqlSessionFactoryBeanName" value="SqlSessionFactory"/>
        <!--指定包名,dao接口的包名,MapperScannerConfigurer会扫描包中的所有接口,把每个接口都执行一次
            得到每个接口的dao对象,创建好的dao对象放到spring容器中
            dao对象默认名称是接口名首字母小写-->
        <property name="basePackage" value="com.myproject.dao"></property>
    </bean>

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

</beans>

创建测试类,获取service对象,通过service调用dao完成数据库的访问

public class MyTest {
    @Test
    public void test01(){
        String config="applicationContex.xml";
        ApplicationContext ctx=new ClassPathXmlApplicationContext(config);
        String names[]=ctx.getBeanDefinitionNames();
        for (String na :
                names) {
            System.out.println(na);
        }
    }

    @Test
    public void testinsertStudent(){
        String config="applicationContex.xml";
        ApplicationContext ctx=new ClassPathXmlApplicationContext(config);
        StudentDao dao= (StudentDao) ctx.getBean("studentDao");
        Student student=new Student("lisi",1005,"15641",20);
        int nums=dao.insertStudent(student);
        System.out.println(nums);
    }

    @Test
    public void testServiceinsertStudent(){
        String config="applicationContex.xml";
        ApplicationContext ctx=new ClassPathXmlApplicationContext(config);
        StudentService service= (StudentService) ctx.getBean("studentService");
        Student student=new Student("lisi",1006,"15641",20);
        int nums=service.addStudent(student);
        System.out.println(nums);
    }

    @Test
    public void testqueryStudents(){
        String config="applicationContex.xml";
        ApplicationContext ctx=new ClassPathXmlApplicationContext(config);
       StudentDao dao= (StudentDao) ctx.getBean("studentDao");
       List<Student> students=dao.selectStudent();
       //spring-mybatis整合中,业务自动提交
        for (Student stu :
                students) {
            System.out.println(stu);
        }
    }
}

一些笔记

把mybatis框架和spring集成在一起,向一个框架一样使用。

用的技术是:ioc 。
为什么ioc:能把mybatis和spring集成在一起,像一个框架, 是因为ioc能创建对象。
可以把mybatis框架中的对象交给spring统一创建, 开发人员从spring中获取对象。
开发人员就不用同时面对两个或多个框架了, 就面对一个spring

mybatis使用步骤,对象

1.定义dao接口 ,StudentDao
2.定义mapper文件 StudentDao.xml
3.定义mybatis的主配置文件 mybatis.xml
4.创建dao的代理对象, StudentDao dao = SqlSession.getMapper(StudentDao.class);

   List<Student> students  = dao.selectStudents();

要使用dao对象,需要使用getMapper()方法,
怎么能使用getMapper()方法,需要哪些条件
1.获取SqlSession对象, 需要使用SqlSessionFactory的openSession()方法。
2.创建SqlSessionFactory对象。 通过读取mybatis的主配置文件,能创建SqlSessionFactory对象

需要SqlSessionFactory对象, 使用Factory能获取SqlSession ,有了SqlSession就能有dao , 目的就是获取dao对象
Factory创建需要读取主配置文件

我们会使用独立的连接池类替换mybatis默认自己带的, 把连接池类也交给spring创建。

==============================================================
通过以上的说明,我们需要让spring创建以下对象
1.独立的连接池类的对象, 使用阿里的druid连接池
2.SqlSessionFactory对象
3.创建出dao对象

需要学习就是上面三个对象的创建语法,使用xml的bean标签。

连接池:多个连接Connection对象的集合, List<Connection>  connlist : connList就是连接池

通常使用Connection访问数据库
Connection conn =DriverManger.getConnection(url,username,password);
Statemenet stmt = conn.createStatement(sql);
stmt.executeQuery();
conn.close();


使用连接池
在程序启动的时候,先创建一些Connection
Connection c1 = ...
Connection c2 = ...
Connection c3 = ...
List<Connection>  connlist = new ArrayLits();
connList.add(c1);
connList.add(c2);
connList.add(c3);

Connection conn = connList.get(0);
Statemenet stmt = conn.createStatement(sql);
stmt.executeQuery();
把使用过的connection放回到连接池
connList.add(conn);


Connection conn1 = connList.get(1);
Statemenet stmt = conn1.createStatement(sql);
stmt.executeQuery();
把使用过的connection放回到连接池
connList.add(conn1);