Mybatis environment construction and example

Keywords: Java MySQL SQL

Current computer tool environment: IDEA, JDK1.8, Mysql5.0, Maven 3.6.1

Steps:

1. Create JAVA WEB project

2. Configure tomcat

3. Load the dependent jar package of mybatis, the dependent jar package of mysql, and the jar packages of junit and hamcrest core (as well as the jar package of log) required for configuration

4. Create a Resources folder under the project directory, make directory as resources

5. Create a test folder under the project directory and make directory as test sources root

6. Create the properties file in the resources directory and the xml file of the core configuration cfg

The root tag of cfg's xml file is configuration, and then configure properties/typeAliases (unnecessary) / environments / maps

Configure under [settings default], configure under [settings id], transactionManager [type jdbc], dataSource [type pooled], and configure property [inherent properties of dataSource driver, url, username, password] under dataSource

Configure mapper under mappers [resource is the mapping path]

7. Create package, dao layer interface, sql mapper xml file and object class of return value under src directory

Write method rules for adding, deleting, modifying and querying in the interface.

The root tag of the sql mapping file is mapper [namespace is the full name of the interface including the package name]. Under the root tag, insert/update/delete/select tags are configured successively, and there is only one sql statement in each tag. For each label, bind the method name of the interface with id, bind the parameter value type with parameterType, and bind the return value object class with resultType [it needs to be the full name of the class with package name or make an alias with typeAliases label]

8. Create a test class in the test folder created in 5

In the interface file of dao layer, use ctrl+shift+t shortcut to create test classes.

Perform the following operations in each method of the test class:

Create SqlSessionFactoryBuilder object b:

SqlSessionFactoryBuilder b=new SqlSessionFactoryBuilder();

Introduce cfg.xml into the Reader object r:

Reader r=Resources.getResourceAsReader("mapping file name");

Create the object f of SqlSessionFactory with the b object and pass the mapping file as a parameter:

SqlSessionFactory f=b.build(r);

Create a SqlSession object using f object s:

SqlSession s=f.openSession(true);

Use the s object to find the mapping file of sql, execute the sql statement of the corresponding method, and complete the operations of adding, deleting, modifying and querying:

s. Getmapper (interface name. class). Method name (argument) in the interface;    // No return value

s. Getmapper (interface name. class). Method name (argument). var in the interface;    // Use the object class that returns the value to receive the return value

cfg.xml file code:

<?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>
    <properties resource="db.properties"/>
    <typeAliases>
        <typeAlias type="kb15002.entity.User" alias="user"/>
    </typeAliases>
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="jdbc"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${user}"/>
                <property name="password" value="${pwd}"/>
            </dataSource>
        </environment>
    </environments>
<mappers>
    <mapper resource="kb15002/dao/UserDao.xml"/>
</mappers>
</configuration>

mapper.xml file code:

<?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="kb15002.dao.UserDao">
    <insert id="insertUserByNameAndPwd" parameterType="string" >
        insert into tbuser(userName, password) value(#{name},#{pwd})
    </insert>
    <update id="updUserByNameAndPwd" parameterType="string">
        update tbuser set password=#{newpwd} where userName=#{name} and password=#{pwd}
    </update>
    <delete id="delUserByNameAndPwd" parameterType="string">
        delete from tbuser where userName=#{name} and password=#{pwd}
    </delete>
    <select id="getUserByNameAndPwd" parameterType="string" resultType="user">
        select * from tbuser where userName=#{name} and password=#{pwd}
    </select>
</mapper>

Test class code: [the calling method shall be written in the method first and then moved outside, otherwise it cannot be recognized]

package kb15002.dao;

import kb15002.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;

import java.io.IOException;
import java.io.Reader;

import static org.junit.Assert.*;

public class UserDaoTest {
    SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
    Reader r=Resources.getResourceAsReader("mybatis002-cfg.xml");
    SqlSessionFactory f = builder.build(r);
    SqlSession session = f.openSession(true);


    public UserDaoTest() throws IOException {
    }


    @Test
    public void getUserByNameAndPwd() throws IOException {
        User u = session.getMapper(UserDao.class).getUserByNameAndPwd("yeli", "1111");
        System.out.println(u);
    }

    @Test
    public void insertUserByNameAndPwd() throws IOException {
        session.getMapper(UserDao.class).insertUserByNameAndPwd("tian","1234");
    }

    @Test
    public void updUserByNameAndPwd() throws IOException {
       session.getMapper(UserDao.class).updUserByNameAndPwd("4444", "tian", "1234");


    }

    @Test
    public void delUserByNameAndPwd() throws IOException {

        session.getMapper(UserDao.class).delUserByNameAndPwd("yeli","ylyl");
    }
}

Posted by EricTRocks on Fri, 24 Sep 2021 07:37:02 -0700