mybatis notes (open)

Keywords: Mybatis xml Java Apache

Development environment jdk1.8 maven mysql8.0

1, guide package

2. Configure config (including write db.properties)

db.properties:

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=UTC

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>

    <properties resource="db.properties">
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </properties>

    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <typeAliases>
        <!--<typeAlias type="com.it.pojo.User" alias="User"></typeAlias>-->
        <package name="com.it.pojo"></package>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com/it/dao/UserMapper.xml"></mapper>
    </mappers>

</configuration>

3. Write MybatisUtil to create a factory

package com.it.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory = null;
    static {
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Connection error!");
        }
    }

    public static SqlSession getSqlsession(){
        return sqlSessionFactory.openSession();
    }
}

4. Write pojo

Test class is User, attribute id, name, pwdd

5. Write dao layer

(1) write interface

package com.it.dao;

import com.it.pojo.User;

import java.util.List;
import java.util.Map;

public interface UserMapping {
   public User getOneUser(int id);
   public List<User> getLimitUser(Map<String,Object> map);
}

(2) implementation interface

a. use profile (alias used)

<?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.it.dao.UserMapping">
    <resultMap id="UserMap" type="user">
        <!--<result column="id" property="id"></result>-->
        <!--<result column="name" property="name"></result>-->
        <result column="pwdd" property="password"></result>
    </resultMap>
    
    <select id="getOneUser" resultType="User" resultMap="UserMap">
        select * from mybatis.user where id = #{id}
    </select>

    <select id="getLimitUser" parameterType="map" resultType="user" resultMap="UserMap">
        select  * from  mybatis.user  limit #{startIndex},#{pageSize}
    </select>
</mapper>

b. use notes

 @Select("select * from mybatis.user where id=#{tid}")
    public Teacher getOneUser(@Param("tid") int id);

 

6, test

     @Test
    public void  testGetOneUser(){
        SqlSession sqlSession = MybatisUtil.getSqlsession();
        UserMapping userMapping = sqlSession.getMapper(UserMapping.class);
        User user = userMapping.getOneUser(1);
//        User user = userMapping.getOneUser(new User(1,"java","0"));
        System.out.println(user);
        sqlSession.close();
    }

 

-----------------

details

Omnipotent map

  @Test
    public void testLimitUser(){
        SqlSession sqlSession = MybatisUtil.getSqlsession();
        UserMapping userMapping = sqlSession.getMapper(UserMapping.class);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("startIndex",0);
        map.put("pageSize",4);
        List<User> users = userMapping.getLimitUser(map);
        for (User user:
             users) {
            logger.info(user);
        }
        sqlSession.close();
    }

Setting in log configuration setting

log4j: document https://mp.csdn.net/postedit/104128706

Relationship correspondence (teacher, student)

Many to one querying teacher information through student s (two implementations)

 <select id="getAllStudent" resultMap="getasStudent">
        select * from student
    </select>
    
    <resultMap id="getasStudent" type="Student">
        <result property="id" column="id"></result>
        <result property="name" column="name"></result>
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association>
    </resultMap>
    
    <select id="getTeacher" resultType="Teacher">
        select * from teacher where id = #{id}
    </select>

    <!--========================================================-->

    <select id="getAllStudent1" resultMap="student_teacher">
        select s.id sid,s.name sname,s.tid stid,t.name tname from mybatis.student s,mybatis.teacher t where s.tid=t.id
    </select>
    <resultMap id="student_teacher" type="Student">
        <result property="id" column="sid"></result>
        <result property="name" column="sname"></result>
        <association property="teacher" javaType="Teacher">
            <result property="id" column="stid"></result>
            <result property="name" column="tname"></result>
        </association>
    </resultMap>

Official documents

https://mybatis.org/mybatis-3/zh/configuration.html

Published 12 original articles, won praise 0, visited 1618
Private letter follow

Posted by Sa177ir on Sun, 02 Feb 2020 10:15:51 -0800