mybatis笔记(完结)

开发环境 jdk1.8 maven mysql8.0

1、导包

2、配置config(包括写db.properties)

db.properties:

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=UTC
//url=jdbc:mysql://localhost:3306/sc01?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&useUnicode=utf8

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、编写MybatisUtil创建工厂

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("连接错误!");
        }
    }

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

4、编写pojo

   测试类为User,属性id、name、pwdd

5、编写dao层

     (1)、编写接口

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)、实现接口

                a.使用配置文件(已使用Aliases)

<?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.使用注解

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

 

6、测试

     @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();
    }

 

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

细节

万能的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中设置

log4j:文档 https://mp.csdn.net/postedit/104128706

关系对应(teacher、student)

  多对一 通过student查询teacher信息(两种实现)

 <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>

一对多的两种实现,建议用第一种,第二种中的collection中的column值为多对一中一(teacher表的id),很绕,这里很绕,姑且这样理解。

 <!--按结果嵌套处理-->
    <select id="getOneTeacher" resultMap="teacherStudent">
        select t.id tid,t.name tname,s.id sid,s.name sname
        from mybatis.teacher t,mybatis.student s
        where t.id=s.tid and  t.id=#{tid}
    </select>

    <resultMap id="teacherStudent" type="Teacher">
        <result property="id" column="tid"></result>
        <result property="name" column="tname"></result>
        <collection property="students" ofType="Student">
            <result property="id" column="sid"></result>
            <result property="name" column="sname"></result>
        </collection>
    </resultMap>

    <!--=============================-->
    <!--按照查询嵌套处理-->

    <select id="getOnerTeacher1" resultMap="teacherStudent1">
        select  * from  mybatis.teacher where  id =#{tid}
    </select>

    <resultMap id="teacherStudent1" type="Teacher">
        <result property="id" column="id"></result>
        <result property="name" column="name"></result>
        <!--collection中的column的id是Student的id-->
        <collection property="students" javaType="ArrayList" ofType="Student" select="getListStudent" column="id"></collection>
    </resultMap>

    <select id="getListStudent" resultType="Student">
        select * from  mybatis.student where  tid = #{tid}
    </select>

类中属性是List<T>javaType中写集合名,是Student写Student,一对多多了一个ofType里面写T类型

官方说明文档

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值