MyBatis学习【一】

MyBatis学习

接口代理开发

搭建环境架构

Maven导入包

POM.XML

 <dependencies>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>

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

        <!--单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!--mybatis日志配置-->
        <!-- 添加slf4j日志api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.20</version>
        </dependency>
        <!-- 添加logback-classic依赖 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!-- 添加logback-core依赖 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.2.3</version>
        </dependency>
    </dependencies>

搭建文件结构

MyBatis学习【一】
映射文件对应的接口文件所在文件夹名称应相同

主文件结构

main.java

mapper: 映射接口包.反射获取调用sql语句

抽象方法接口

pojo: 主类包,数据库表的实现类
utils: 工具类包

main.resources

MyBatis-config配置文件

可以到MyBatis官网找到相关配置参数

<?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="mapUnderscoreToCamelCase" value="true"/>
        <!--开启二级缓存,必须关掉上一个链接才有效-->
        <setting name="cacheEnabled" value="true"/>
    </settings>
    <typeAliases>
        <!--目标类,包扫描,扫描包中的所有类,取别名,别名就是类名-->
        <package name="com.itheima.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--配置连接池需要的参数-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///exercise"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
    <!--包扫描,扫描包中的所有映射接口文件-->
       <package name="com.itheima.mapper"/>
    </mappers>
</configuration>

logback.xml是与日志相关配置文件

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!--CONSOLE :表示当前的日志信息是可以输出到控制台的。-->
    <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>[%level] %blue(%d{HH:mm:ss.SSS}) %cyan([%thread]) %boldGreen(%logger{15}) - %msg %n</pattern>
        </encoder>
    </appender>

    <logger name="com.itheima" level="DEBUG" additivity="false">
        <appender-ref ref="Console"/>
    </logger>

    <!--level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF, 默认debug
      <root>可以包含零个或多个<appender-ref>元素,标识这个输出位置将会被本日志级别控制。-->
    <root level="DEBUG">
        <appender-ref ref="Console"/>
    </root>
</configuration>

Mapper.xml 映射文件

以User.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.itheima.mapper.UserMapper">
    <resultMap id="UserInfoMap" type="UserInfo" autoMapping="true">
        <id column="id" property="id"/>
        <!--<result column="height" property="height"/>
        <result column="weight" property="weight"/>
        <result column="married" property="married"/>-->
    </resultMap>

    <resultMap id="OrderMap" type="Order" autoMapping="true">
        <id column="oid" property="oId"/>
        <!--<result column="user_id" property="userId"/>-->
        <!--<result column="number" property="number"/>-->
        <!--<result column="create_time" property="createTime"/>-->
        <!--<result column="note" property="note"/>-->
    </resultMap>
    
    <resultMap id="UserMap" type="User" autoMapping="true">
        <id column="id" property="id"/>
        <!--<result column="username" property="username"/>
        <result column="birthday" property="birthday"/>
        <result column="sex" property="sex"/>
        <result column="address" property="address"/>-->

        <!--association: 配置一对一  property属性: 类中成员变量名-->
        <association property="userInfo" resultMap="UserInfoMap"/>

        <!--collection: 配置一对多   property属性: 类中成员变量名-->
        <collection property="orders" resultMap="OrderMap"/>
        <collection property="roles" javaType="List" ofType="Role">
            <id column="role_id" property="roleId"/>
            <result column="role_name" property="roleName"/>
            <result column="role_detail" property="roleDetail"/>
        </collection>
    </resultMap>

    <!--多表查询,查询结果有多张表的数据,需要使用resultMap,手动指定查询结果和类中成员变量的对应关系
        注意: 多表查询表中字段名和类中成员变量相同的也要指定关系,
        或者使用 autoMapping="true",但是主键相同也要配置
        -->
    <select id="findUserAndInfo" resultMap="UserMap">
        SELECT * FROM USER INNER JOIN user_info ON user.`id`=user_info.`id` WHERE user.id=#{uid};
    </select>

    <!--一对多查询用户和多个订单-->
    <select id="findUserAndOrders" resultMap="UserMap">
        SELECT * FROM USER INNER JOIN `order` ON user.`id`=`order`.`user_id` WHERE user.`id`=#{uid};
    </select>

    <!--一个用户包含多个角色 (一对多)-->
    <select id="findUserAndRoles" resultMap="UserMap">
          SELECT * FROM USER INNER JOIN user_role ON user.`id`=user_role.`user_id` INNER JOIN role ON role.`role_id`=user_role.`role_id` WHERE user.`id`=#{uid};
    </select>

    <resultMap id="RoleMap" type="Role" autoMapping="true">
        <id column="role_id" property="roleId"/>
        <!--<result column="role_name" property="roleName"/>-->
        <!--<result column="role_detail" property="roleDetail"/>-->

        <collection property="users" javaType="List" ofType="User" autoMapping="true">
            <id column="id" property="id"/>
            <!--<result column="username" property="username"/>-->
            <!--<result column="birthday" property="birthday"/>-->
            <!--<result column="sex" property="sex"/>-->
            <!--<result column="address" property="address"/>-->
        </collection>
    </resultMap>
    <!--一个角色包含多个用户 (一对多)-->
    <select id="findRoleAndUsers" resultMap="RoleMap">
        SELECT * FROM USER INNER JOIN user_role ON user.`id`=user_role.`user_id` INNER JOIN role ON role.`role_id`=user_role.`role_id` WHERE role.`role_id`=#{rid};
    </select>
</mapper>

有过报错
Cause: org.xml.sax.SAXParseException; lineNumber: 4; columnNumber: 45; 文档根元素 “mapper” 必须匹配 DOCTYPE 根 “null”。
解决:

原(自生成头文件):

<?xml version="1.0" encoding="utf-8" ?>
<mapper xmlns="http://mybatis.org/schema/mybatis-mapper"
 namespace="*.mapper.UserMapper">

改为:

<?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="*.UserMapper">

main.test

test: 测试类

Utils:

public class SqlSessionFactoryUtils {
    private SqlSessionFactoryUtils(){}
    private  static SqlSessionFactory sqlSessionFactory;
    static {
        String s="mybatis-config.xml";
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream(s);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

        } catch (IOException e) {

            System.out.println("链接池初始化失败"+e.toString());
        }
    }
    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }

}

测试:

 @Test
    public void findSingleUserByID(){
       SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User userByID = mapper.findUserByID(1);
        System.out.println(userByID);

    }
上一篇:Python中join()方法和os.path.join()方法


下一篇:Js前端-路由管理器函数