Spring (four) spring integration mybatis

Spring (four) spring integration mybatis

Article Directory

step:

1. Create a new maven project

Insert picture description here

2. Add maven dependency

1) Spring dependency

 <!--spring依赖 ioc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.15.RELEASE</version>
        </dependency>

2) Mybatis dependency

 <!--mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

3) mysql driver

 <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>

4) Spring's transaction dependency

        <!--是做spring事务用到的-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.15.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.15.RELEASE</version>
        </dependency>

5) Dependency of mybatis and spring integration

​ Officially used by mybatis, used to create the SqlSesissonFactory and dao objects of mybatis in the spring project

<!--mybatis与spring集成-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>

6) Alibaba's druid database connection pool

<!--阿里公司的druid数据库连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>

Final pom file

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

    <name>ch06-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.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <!--spring依赖 ioc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.15.RELEASE</version>
        </dependency>
        <!--是做spring事务用到的-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.15.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.15.RELEASE</version>
        </dependency>

        <!--mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <!--mybatis与spring集成-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>

        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>

        <!--阿里公司的druid数据库连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>

    </dependencies>

    <build>
        <!--目的是吧src/main/java目录中的xml文件包含到输出结果中。-->
        <resources>
            <resource>
                <directory>src/main/java</directory><!--所在的目录-->
                <includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
    </build>
</project>

3. Create an entity class

Create entity class Users.java under the entity package

package com.entity;

/**
 * Created by IntelliJ IDEA.
 * User: LvHaoIT (asus)
 * Date: 2021/5/24
 * Time: 9:44
 */
public class Users {
    private Integer userId;
    private String userName;
    private String password;
    private String sex;
    private String email;

    public Users() {
    }

    public Users(String userName, String password, String sex, String email) {
        this.userName = userName;
        this.password = password;
        this.sex = sex;
        this.email = email;
    }

    public Users(Integer userId, String userName, String password, String sex, String email) {
        this.userId = userId;
        this.userName = userName;
        this.password = password;
        this.sex = sex;
        this.email = email;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Users{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                ", sex='" + sex + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

4. Create dao interface and mapper file

1) Create the UsersDao interface

package com.dao;

import com.entity.Users;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: LvHaoIT (asus)
 * Date: 2021/6/3
 * Time: 17:05
 */
public interface UsersDao {
    int insertUsers(Users user);

    List<Users> selectUsers();
}

2) Create UsersDao.xml (mapping) file

​ Only used to write sql statements operated in usersDao

<?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.dao.UsersDao">
    <insert id="insertUsers">
    insert into Users values(#{userId},#{userName},#{password},#{sex},#{email})
    </insert>

    <select id="selectUsers" resultType="com.entity.Users">
        select * from Users
    </select>

</mapper>

5. Create mybatis main configuration file

​ Used to set the entity class bean alias, the first letter lowercase alias, and load all dao.xml files (sql mapping files)

<?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>
    <!--设置全局事务:显示日志-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <!--设置别名-->
    <typeAliases>
        <!--name:实体类所在的包名-->
        <package name="com.entity"/>
    </typeAliases>

    <!-- sql mapper(sql映射文件)的位置-->
    <mappers>
        <!--这个包中的所有mappe.xml一次性都能加载-->
        <!--告诉 mybatis 要执行的 sql 语句的位置-->
        <package name="com.dao"/>
    </mappers>
</configuration>



6. Create Service interface and implementation class, the attribute is dao.

1) Under the service package, create an interface UserService

package com.service;

import com.entity.Users;
import java.util.List;
/**
 * Created by IntelliJ IDEA.
 * User: LvHaoIT (asus)
 * Date: 2021/6/3
 * Time: 18:42
 */
public interface UserService {

    int addUsers(Users user);

    List<Users> queryUsers();
}

2) Create the implementation class UserServiceImlp under the service package Impl

One of the attributes is private UsersDao usersDao;

And it has a set method, because in the spring configuration file

To assign a value to it through set injection

package com.service.Impl;

import com.dao.UsersDao;
import com.entity.Users;
import com.service.UserService;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: LvHaoIT (asus)
 * Date: 2021/6/3
 * Time: 18:45
 */
public class UserServiceImpl implements UserService {

    //引用类型dao
    private UsersDao usersDao;

    //使用set注入,赋值
    public void setUsersDao(UsersDao usersDao) {
        this.usersDao = usersDao;
    }

    @Override
    public int addUsers(Users user) {
        int nums = usersDao.insertUsers(user);
        return nums;
    }

    @Override
    public List<Users> queryUsers() {
        return usersDao.selectUsers();
    }
}

7. Create a spring configuration file:

The object that declares mybatis is handed over to spring to create

1) DataSource DataSource

​ Use the druid connection pool, in which to declare the connection properties

   <!--声明数据源DataSource,作用是连接数据库-->
    <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.maxActive}"/>
    </bean>

2)SqlSessionFactory

​ The statement is the SqlSessionFactoryBean class provided in mybatis,

​ Create SqlSessionFactory inside this class

​ It has two properties:

  1. dataSouerce: database information, injected by ref reference, so the value fills in the id value of dataSouerce above
  2. configLocation: The main configuration file used to import mybatis, the value is **classpath:**mybatis.xml
<!--声明的是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>

3) Dao object

​ Create dao objects, use SqlSession's getMapper (UsersDao.class)
​ MappersScannerConfigurer: call getmapper () internally to generate proxy objects for each dao interface

Attributes:

  1. sqlSessionFactoryBeanName : Write the id value of the above SqlSessionFactory
  2. basePackage : Write the package name where the dao interface is located. It can execute the getMapper() method for each interface, so that you can create a dao object for each interface and put these objects in the spring container. The id value of the object is Names beginning with lowercase
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定SqlSessionFactory对象的id-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!--指定包名,包名是你dao接口的所在的包名
            MapperScannerConfigurer会扫描这个包中的所有接口,吧每个接口都执行一遍getMapper()方法
            得到每个接口的dao对象,创建好的dao对象放入到spring容器中
        -->
        <property name="basePackage" value="com.dao"/>

    </bean>

4) Create database configuration information jdbc.propties

jdbc.url=jdbc:mysql://127.0.0.1:3306/kaoshixitong?serverTimezone=UTC
jdbc.username=root
jdbc.password=******
jdbc.maxActive=20           //最大连接数量

​ Then declare the location in the spring configuration file

​ and use the value in the way of ${key}

<!--把数据库的配置信息,写入一个独立文件中,然后调用
        先要让spring知道jdbc.properties文件位置
    -->
    <context:property-placeholder location="jdbc.properties"/>

5) Declare custom service

​ Put the implementation class of service into the spring container

And using the set injection (Property) manner, dao layer object corresponding to the id value assigned to the ((i.e. dao object created 3))

    <!--声明service-->
    <bean id="usersService" class="com.service.Impl.UserServiceImpl">
        <property name="usersDao" ref="usersDao"/>
    </bean>

8. Create a test class

Get the Service object, call dao through service to complete database access

package com;

import com.entity.Users;
import com.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: LvHaoIT (asus)
 * Date: 2021/6/3
 * Time: 20:58
 */
public class myTest01 {
    @Test
    public void test01() {
        String config = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(config);
        String name[] = ac.getBeanDefinitionNames();
        for (String a : name) {
            System.out.println("容器中对象名:===========" + a);
        }
    }


    @Test
    public void testDaoSelect() {
        String config = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(config);
        UserService userService = (UserService) ac.getBean("usersService");
        List<Users> list = userService.queryUsers();
        for (Users user : list) {
            System.out.println(user);
        }

    }

    @Test
    public void testDaoInsert() {
        String config = "applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(config);
        UserService userService = (UserService) ac.getBean("usersService");
        int result = userService.addUsers(new Users(8, "lvhao", "123", "男", "[email protected]"));
        System.out.println("result=" + result);

    }
}