Mybatis related configuration properties

RoleMapper

package com.itheima.sh.dao;


import com.itheima.sh.pojo.Role;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface RoleMapper {
    //分页查询角色以及对应的用户和权限信息
    List<Role> queryAllRolesAndUsersAndPermi(@Param("startIndex") int startIndex, @Param("pageSize") int pageSize);

}

UserMapper

package com.itheima.sh.dao;


import com.itheima.sh.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface UserMapper {
    //分页查询用户
    List<User> queryAllUsersAndRoles(@Param("startIndex") int startIndex, @Param("pageSize")int pageSize);
    //根据用户id修改用户名称 密码
    @Update("update t_user set username=#{username},password=#{password} where id=#{id}")
    void updateUserById(User user);
}

UserRoleMapper

package com.itheima.sh.dao;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;

public interface UserRoleMapper {
    //根据用户id删除中间表数据
    @Delete("delete from t_user_role where user_id=#{id}")
    void deleteUserAndRoleByUID(@Param("id") String id);
    //向中间表插入新的数据
    @Insert("insert into t_user_role values(#{uid},#{roleId})")
    void addUserAndRoleID(@Param("uid")String id, @Param("roleId")String roleId);
}

Permission

package com.itheima.sh.pojo;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 权限
 */
public class Permission implements Serializable{
    private String id;
    private String name; // 权限名称
    private String keyword; // 权限关键字,用于权限控制
    private String description; // 描述
    //一个权限可以保存多个角色
    private List<Role> roles = new ArrayList<Role>(0);

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getKeyword() {
        return keyword;
    }

    public void setKeyword(String keyword) {
        this.keyword = keyword;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

    @Override
    public String toString() {
        return "Permission{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", keyword='" + keyword + '\'' +
                ", description='" + description + '\'' +
                ", roles=" + roles +
                '}';
    }
}

Role

package com.itheima.sh.pojo;

import java.util.ArrayList;
import java.util.List;

/*
    角色
 */
public class Role {

    private String id;
    private String name;
    private String keyword;
    private String description;
    //一个角色可以保存多个用户
    private List<User> users = new ArrayList<User>(0);
    //一个角色可以保存多个权限
    private List<Permission> permissions = new ArrayList<Permission>(0);

    @Override
    public String toString() {
        return "Role{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", keyword='" + keyword + '\'' +
                ", description='" + description + '\'' +
                ", users=" + users +
                ", permissions=" + permissions +
                '}';
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getKeyword() {
        return keyword;
    }

    public void setKeyword(String keyword) {
        this.keyword = keyword;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

    public List<Permission> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<Permission> permissions) {
        this.permissions = permissions;
    }
}

User

package com.itheima.sh.pojo;

import java.util.ArrayList;
import java.util.List;
/*
    用户
 */
public class User {
    private String id;
    private String username;
    private String password;
    private String email;
    private String createTime;
    private String updateTime;
    private String remark;
    private List<String> roleIds;
    //一个用户可以保存多个角色
    private List<Role> roles = new ArrayList<Role>(0);

    public List<String> getRoleIds() {
        return roleIds;
    }

    public void setRoleIds(List<String> roleIds) {
        this.roleIds = roleIds;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    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 getEmail() {
        return email;
    }

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

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    public String getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(String updateTime) {
        this.updateTime = updateTime;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", createTime='" + createTime + '\'' +
                ", updateTime='" + updateTime + '\'' +
                ", remark='" + remark + '\'' +
                ", roleIds=" + roleIds +
                ", roles=" + roles +
                '}';
    }
}

RoleServiceImpl

package com.itheima.sh.service;

import com.itheima.sh.dao.RoleMapper;
import com.itheima.sh.pojo.Role;
import com.itheima.sh.util.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class RoleServiceImpl {
    public List<Role> queryAllRolesAndUsersAndPermi(int startIndex, int pageSize) {
        //1.获取会话工厂对象
        SqlSession sqlSession = SqlSessionUtil.getSqlSession(false);
        //2.获取接口代理对象
        RoleMapper mapper = sqlSession.getMapper(RoleMapper.class);
        //3.使用接口代理对象调用接口中的方法
        List<Role> roleList = mapper.queryAllRolesAndUsersAndPermi(startIndex,pageSize);
        //4.释放资源
        sqlSession.close();
        //5.返回集合给web层
        return roleList;
    }
}

UserServiceImpl

package com.itheima.sh.service;

import com.itheima.sh.dao.UserMapper;
import com.itheima.sh.dao.UserRoleMapper;
import com.itheima.sh.pojo.User;
import com.itheima.sh.util.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class UserServiceImpl {
    public List<User> queryAllUsersAndRoles(int startIndex, int pageSize) {
        //1.获取会话工厂对象
        SqlSession sqlSession = SqlSessionUtil.getSqlSession(false);
        //2.获取接口代理对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //3.使用接口代理对象调用接口中的分页查询用户和角色的方法
        List<User> userList = mapper.queryAllUsersAndRoles(startIndex,pageSize);
        //4.释放资源
        sqlSession.close();
        //5.返回集合给web层的调用者
        return userList;

    }
    //修改用户方法
    public void updateUserById(User user) {
        //1.获取会话工厂对象
        SqlSession sqlSession = SqlSessionUtil.getSqlSession(true);
        //2.获取接口代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        UserRoleMapper userRoleMapper = sqlSession.getMapper(UserRoleMapper.class);

        //3.使用UserMapper接口代理对象调用UserMapper接口中根据id更新用户的方法
        userMapper.updateUserById(user);

        //4.使用UserRoleMapper接口代理对象调用UserRoleMapper的方法根据用户id删除中间表t_user_role中有关当前用户id所有的信息
        userRoleMapper.deleteUserAndRoleByUID(user.getId());

        //5.使用UserRoleMapper接口代理对象调用UserRoleMapper的方法将当前用户id和新的角色id插入到中间表t_user_role中
        //注意在User实体类中使用集合private List<String> roleIds;保存多个角色id,因为一个用户可以有多个角色
        //这里需要遍历集合roleIds取出每个角色id
        List<String> roleIds = user.getRoleIds();
        //遍历
        /*
            admin(1)   原来角色 管理员(1) 会员(2)
            admin(1)   新的角色 会员(2)  游客(3)
         */
        for (String roleId : roleIds) {
            //6.将当前用户的用户id和角色id插入到中间表t_user_role
            userRoleMapper.addUserAndRoleID(user.getId(),roleId);
        }
    }
}

SqlSessionUtil

package com.itheima.sh.util;

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

/*
    工具类特点:
        1.位于util包
        2.私有化构造方法
        3.提供静态方法
 */
public class SqlSessionUtil {
    private static SqlSessionFactory factory = null;

    // 2.私有化构造方法
    private SqlSessionUtil() {
    }

    //静态代码块:类加载就执行获取工厂对象
    static {
        try {
            //1.获取工厂创造类对象
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            //2.获取会话工厂对象
            factory = builder.build(Resources.getResourceAsStream("mybatis-config.xml"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 3.提供静态方法
    //提供会话对象,设置自动提交事务
    public static SqlSession getSqlSession() {

        SqlSession sqlSession = factory.openSession(true);
        //返回会话对象
        return sqlSession;
    }

    //提供会话对象,设置自动提交事务
    public static SqlSession getSqlSession(boolean isAutoCommit) {
        SqlSession sqlSession = factory.openSession(isAutoCommit);
        //返回会话对象
        return sqlSession;
    }

    //编写静态方法接收会话对象,手动提交事务并且关闭会话对象
    public static void commitAndClose(SqlSession sqlSession) {
        //防止空指针,判断
        if (sqlSession != null) {
            //一切正常提交事务
            sqlSession.commit();
            //关闭会话对象
            sqlSession.close();
        }
    }

    public static void commit(SqlSession sqlSession) {
        //防止空指针,判断
        if (sqlSession != null) {
            //一切正常提交事务
            sqlSession.commit();

        }
    }

    public static void close(SqlSession sqlSession) {
        //防止空指针,判断
        if (sqlSession != null) {
           sqlSession.close();

        }
    }

    //编写静态方法接收会话对象,回滚事务并且关闭会话对象
    public static void rollbackAndClose(SqlSession sqlSession) {
        //防止空指针,判断
        if (sqlSession != null) {
            //出现正常回顾事务
            sqlSession.rollback();
            //关闭会话对象
            sqlSession.close();
        }
    }

}

QueryAllRolesAndUsersAndPermi

package com.itheima.sh.web;

import com.itheima.sh.pojo.Role;
import com.itheima.sh.service.RoleServiceImpl;

import java.util.List;
import java.util.Scanner;

/*
    分页查询角色和对应的用户以及权限信息
    入口:
 */
public class QueryAllRolesAndUsersAndPermi {
    public static void main(String[] args) {
        //1.创建键盘录入的对象
        Scanner sc = new Scanner(System.in);
        //2.提示
        System.out.println("请输入起始索引:");
        //获取
        int startIndex = sc.nextInt();//起始索引

        System.out.println("请输入每页条数:");
        //获取
        int pageSize = sc.nextInt();//每页条数

        //3.创建业务层对象
        RoleServiceImpl roleService = new RoleServiceImpl();
        //4.使用业务层对象调用查询角色和对应的用户以及权限信息
        /*
            roleList = [Role{id=1, name='管理员', keyword='ROLE_ADMIN', description='这是管理员',
                            users=[User{id=1, username='admin', password='123', email='[email protected]',
                                                        createTime='2021-12-05 14:50:35.0', updateTime='2021-12-05 14:50:35.0',
                                                                    remark='null', roleIds=null, roles=[]},
                                  User{id=4, username='wangwu', password='123', email='[email protected]',
                                                                    createTime='2021-12-05 14:50:35.0',
                                                                    updateTime='2021-12-05 14:50:35.0',
                                                                     remark='null', roleIds=null, roles=[]},
                                 User{id=6, username='tianqi', password='123', email='[email protected]',
                                                                      createTime='2021-12-05 14:50:35.0',
                                                                      updateTime='2021-12-05 14:50:35.0', remark='null',
                                                                      roleIds=null, roles=[]},
                                User{id=8, username='杨幂', password='123', email='[email protected]', createTime='2021-12-05 14:50:35.0', updateTime='2021-12-05 14:50:35.0', remark='null', roleIds=null, roles=[]},
                                User{id=9, username='李沁', password='123', email='[email protected]', createTime='2021-12-05 14:50:35.0', updateTime='2021-12-05 14:50:35.0', remark='null', roleIds=null, roles=[]},
                                User{id=10, username='赵丽颖', password='123', email='[email protected]', createTime='2021-12-05 14:50:35.0', updateTime='2021-12-05 14:50:35.0', remark='null', roleIds=null, roles=[]}],
                           permissions=[com.itheima.sh.pojo.Permission@691a7f8f, com.itheima.sh.pojo.Permission@50a7bc6e, com.itheima.sh.pojo.Permission@161b062a, com.itheima.sh.pojo.Permission@17c1bced]}, Role{id=2, name='会员', keyword='ROLE_MEMBER', description='这是会员', users=[User{id=1, username='admin', password='123', email='[email protected]', createTime='2021-12-05 14:50:35.0', updateTime='2021-12-05 14:50:35.0', remark='null', roleIds=null, roles=[]}, User{id=2, username='zhansan', password='123', email='[email protected]', createTime='2021-12-05 14:50:35.0', updateTime='2021-12-05 14:50:35.0', remark='null', roleIds=null, roles=[]}, User{id=3, username='lisi', password='123', email='[email protected]', createTime='2021-12-05 14:50:35.0', updateTime='2021-12-05 14:50:35.0', remark='null', roleIds=null, roles=[]}, User{id=5, username='zhaoliu', password='123', email='[email protected]', createTime='2021-12-05 14:50:35.0', updateTime='2021-12-05 14:50:35.0', remark='null', roleIds=null, roles=[]}, User{id=8, username='杨幂', password='123', email='[email protected]', createTime='2021-12-05 14:50:35.0', updateTime='2021-12-05 14:50:35.0', remark='null', roleIds=null, roles=[]}, User{id=10, username='赵丽颖', password='123', email='[email protected]', createTime='2021-12-05 14:50:35.0', updateTime='2021-12-05 14:50:35.0', remark='null', roleIds=null, roles=[]}], permissions=[com.itheima.sh.pojo.Permission@2d9d4f9d, com.itheima.sh.pojo.Permission@4034c28c]}]
         */
        List<Role> roleList=roleService.queryAllRolesAndUsersAndPermi(startIndex,pageSize);
        System.out.println(roleList.size());//2
        //5.输出
        System.out.println("roleList = " + roleList);
    }
}

QueryAllUsersAndRoles

package com.itheima.sh.web;

import com.itheima.sh.pojo.User;
import com.itheima.sh.service.UserServiceImpl;

import java.util.List;
import java.util.Scanner;

/*
    需求:分页查询用户和对应的角色信息,然后将信息输出到idea控制台。
    入口
 */
public class QueryAllUsersAndRoles {
    public static void main(String[] args) {
        //1.创建键盘录入的对象
        Scanner sc = new Scanner(System.in);
        //2.提示
        System.out.println("请输入起始索引:");
        //获取
        int startIndex = sc.nextInt();//起始索引

        System.out.println("请输入每页条数:");
        //获取
        int pageSize = sc.nextInt();//每页条数
        //3.创建业务层对象
        UserServiceImpl userService = new UserServiceImpl();
        //4.使用业务层对象调用业务层分页查询用户和角色的方法
        //将键盘录入的起始索引和每页条数传递到业务层
        //分页查询的是多个用户存储到list集合中
        List<User> userList = userService.queryAllUsersAndRoles(startIndex, pageSize);
        //5.判断集合是否有数据
        if (userList != null && userList.size() != 0) {
            //集合有数据
            /*
                User{id=1, username='admin', password='123', email='[email protected]', createTime='2021-12-05 14:50:35.0',
                    updateTime='2021-12-05 14:50:35.0', remark='null', roleIds=null,
                    roles=[Role{id=1, name='管理员', keyword='ROLE_ADMIN', description='这是管理员',
                    users=[], permissions=[]}, Role{id=2, name='会员', keyword='ROLE_MEMBER',
                    description='这是会员', users=[], permissions=[]}]}
                User{id=2, username='zhansan', password='123', email='[email protected]', createTime='2021-12-05 14:50:35.0', updateTime='2021-12-05 14:50:35.0', remark='null', roleIds=null, roles=[Role{id=2, name='会员', keyword='ROLE_MEMBER', description='这是会员', users=[], permissions=[]}]}
                User{id=3, username='lisi', password='123', email='[email protected]', createTime='2021-12-05 14:50:35.0', updateTime='2021-12-05 14:50:35.0', remark='null', roleIds=null, roles=[Role{id=2, name='会员', keyword='ROLE_MEMBER', description='这是会员', users=[], permissions=[]}]}


             */
            userList.forEach(System.out::println);
        }else{
            //没查询到数据
            System.out.println("没有用户");
        }
    }
}

UpdateUserWeb

package com.itheima.sh.web;

import com.itheima.sh.pojo.User;
import com.itheima.sh.service.UserServiceImpl;

import java.util.ArrayList;

public class UpdateUserWeb {
    public static void main(String[] args) {
        /*
            需求:修改id是1的用户的密码为456,用户名为刘德华,扮演角色变为游客(提示:游客角色id是3)和会员(提示:会员角色id是2)
         */
        //1.创建实体类对象
        User user = new User();
        //2.向user对象中添加数据
        user.setId("1");//修改用户的id
        user.setUsername("刘德华");//用户的新用户名
        user.setPassword("456");//用户的新密码
        //创建集合保存当前用户新角色的id
        ArrayList<String> list = new ArrayList<>();
        list.add("2");//会员角色id是2
        list.add("3");//游客角色id是3
        user.setRoleIds(list);
        //3.创建业务层对象
        UserServiceImpl userService = new UserServiceImpl();
        //4.调用修改方法
        userService.updateUserById(user);
    }
}

RoleMapper.xml

<?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">
<!--
映射文件
namespace 指定接口的类全名
-->
<mapper namespace="com.itheima.sh.dao.RoleMapper">
    <resultMap id="queryAllRolesAndUsersAndPermiResultMap" type="Role" autoMapping="true">
        <!--    配置t_role表和实体类Role的关系    -->
        <id column="rid" property="id"/>
        <result column="rname" property="name"/>
        <result column="rkwd" property="keyword"/>
        <result column="rdes" property="description"/>
        <!--
            配置关联t_user表,角色和用户属于一对多,使用collection
                1) property="users" 表示Role实体类中保存多个用户的容器对象名  private List<User> users = new ArrayList<User>(0);
                2) ofType="User" 表示容器的泛型类型

        -->
        <collection property="users" ofType="User" autoMapping="true">
            <!--    配置t_user表和实体类User的关系    -->
            <id column="id" property="id"/>
        </collection>

        <!--
            配置关联t_permission表,角色和权限属于一对多,使用collection
                1) property="permissions" 表示Role实体类中保存多个权限的容器对象名
                        private List<Permission> permissions = new ArrayList<Permission>(0);
                2) ofType="Permission" 表示容器的泛型类型
        -->
        <collection property="permissions" ofType="Permission" autoMapping="true">
            <!--    配置t_permission表和实体类Permission的关系    -->
            <id column="pid" property="id"/>
            <result column="pname" property="name"/>
            <result column="pkwd" property="keyword"/>
            <result column="pdes" property="description"/>
        </collection>
    </resultMap>
    <!--
         //分页查询角色以及对应的用户和权限信息
        List<Role> queryAllRolesAndUsersAndPermi(@Param("startIndex") int startIndex, @Param("pageSize") int pageSize);
    -->
    <select id="queryAllRolesAndUsersAndPermi" resultMap="queryAllRolesAndUsersAndPermiResultMap">
        select temp.id rid,temp.name rname,temp.keyword rkwd,temp.description rdes,
               u.*,p.id pid,p.name pname,p.keyword pkwd,p.description pdes
        from (select * from t_role limit #{startIndex},#{pageSize}) temp
        inner join t_user_role ur
        inner join t_user u
        inner join t_role_permission rp
        inner join t_permission p
        on temp.id=ur.role_id and ur.user_id=u.id and temp.id=rp.role_id and rp.permission_id = p.id
    </select>
</mapper>

UserMapper.xml

<?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">
<!--
映射文件
namespace 指定接口的类全名
-->
<mapper namespace="com.itheima.sh.dao.UserMapper">
    <!--
        1.type="User" : 相当于之前的resultType,表示接口的方法返回类型,这里方法:
              List<User> queryAllUsersAndRoles(@Param("startIndex") int startIndex, @Param("pageSize")int pageSize);
         的返回值是List<User>,那么type属性值位置书写集合泛型类型

    -->
    <resultMap id="queryAllUsersAndRolesResultMap" type="User" autoMapping="true">
        <!--
            配置t_user表和User实体类关系
        -->
        <id column="id" property="id"/>
        <!--
            配置关联的t_role表,因为一个用户有多个角色,所以这里是一对多,使用标签collection
            private List<Role> roles = new ArrayList<Role>(0);
            1.property="roles" 表示User实体类中保存多个角色容器对象名
            2.ofType="Role" : 表示保存角色的容器中的泛型类型
        -->
        <collection property="roles" ofType="Role" autoMapping="true">
            <!--
                配置t_role表和Role实体类关系
            -->
            <id column="rid" property="id"/>
        </collection>
    </resultMap>
    <!--
         //分页查询用户
        List<User> queryAllUsersAndRoles(@Param("startIndex") int startIndex, @Param("pageSize")int pageSize);
    -->
   <select id="queryAllUsersAndRoles" resultMap="queryAllUsersAndRolesResultMap">
       select temp.*,r.id rid,r.name,r.keyword,r.description
       from (select * from t_user limit #{startIndex},#{pageSize})  temp
       inner join t_user_role ur
       inner join t_role r
       on temp.id = ur.user_id and ur.role_id = r.id;
   </select>
</mapper>

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/day0801
jdbc.username=root
jdbc.password=1234

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!--
        CONSOLE :表示当前的日志信息是可以输出到控制台的。
    -->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <!--输出流对象 默认 System.out 改为 System.err-->
        <target>System.out</target>
        <encoder>
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度
                %msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level]  %c [%thread] : %msg%n</pattern>
        </encoder>
    </appender>

    <!-- File是输出的方向通向文件的 -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
            <charset>utf-8</charset>
        </encoder>
        <!--日志输出路径-->
        <file>C:/code/itheima-data.log</file>
        <!--指定日志文件拆分和压缩规则-->
        <rollingPolicy
                class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <!--通过指定压缩文件名称,来确定分割文件方式-->
            <fileNamePattern>C:/code/itheima-data2-%d{yyyy-MMdd}.log%i.gz</fileNamePattern>
            <!--文件拆分大小-->
            <maxFileSize>1MB</maxFileSize>
        </rollingPolicy>
    </appender>

    <!--

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

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"></properties>
    <!--settings-->
    <settings>
        <!--开启驼峰自动映射-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!--别名-->
    <typeAliases>
        <package name="com.itheima.sh.pojo"></package>
    </typeAliases>
    <!--mybatis环境的配置
        一个核心配置文件,可以配置多个运行环境,default默认使用哪个运行环境
    -->
    <environments default="development">
        <!--通常我们只需要配置一个就可以了, id是环境的名字 -->
        <environment id="development">
            <!--事务管理器:由JDBC来管理-->
            <!--
                事务管理器type的取值:
                1. JDBC:由JDBC进行事务的管理
                2. MANAGED:事务由容器来管理,后期学习Spring框架的时候,所有的事务由容器管理
            -->
            <transactionManager type="JDBC"/>
            <!--数据源的配置:mybatis自带的连接池-->
            <!--
                数据源:
                1. POOLED:使用mybatis创建的连接池
                2. UNPOOLED:不使用连接池,每次自己创建连接
                3. JNDI:由服务器提供连接池的资源,我们通过JNDI指定的名字去访问服务器中资源。
            -->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>

    </environments>
    <!--映射器-->
    <mappers>
        <!--加载其它的映射文件 注:注解开发是点号-->
        <!-- <package name="com.itheima.sh.dao"></package>-->
        <!--加载其它的映射文件 注:不是点号-->
        <!--<mapper resource="org/mybatis/example/BlogMapper.xml"/>-->
        <!--
            加载其它的映射文件 xml形式
                包扫描方式加载mapper映射文件,说明:
                1. 要求mapper映射文件,与mapper接口要放在同一个目录
                2. 要求mapper映射文件的名称,与mapper接口的名称要一致
            -->
        <package name="com.itheima.sh.dao"></package>
    </mappers>
</configuration>

Summarize

Today's summary:
1. Mapping files to realize dynamic sql:**************************
    1. <if test="judgment condition">
           text
         < /if>
     If the judgment condition is true, then execute the text of the if tag, if it is false, it will not execute

     2. Multi-branch or choose one
     <choose>
            <when ​​test="judgment condition">
                 text 1
            </when>
            <when ​​test="judgment condition">
                text 2
            </when>
            <otherwise>
                 text 3
            </otherwise>
        </choose>
    If the condition of a when is met, execute the corresponding text and not execute the following content, if the condition is not met, continue to execute the following content
    If all the judgment conditions in the when are false, then execute the otherwise text

    3. The role of the <where> tag: 1) Add the where keyword 2) Remove redundant and and or

    4. The role of the <set> tag: 1) Add the set keyword 2) Remove redundant commas

    5. Used to traverse arrays or collections
        <foreach collection="array or collection name" item="element" separator="element separator" open="start with what" close="end with what"> #{element
                    }
                < /foreach>

2. Multi-table query: *************************
    1) One-to-one query:
        <resultMap id="queryOneToOneResultMap" type="Order" autoMapping="true">
            <!-- configures the mapping relationship between the tb_order table and the entity class Order -->
            <id column="oid" property="id"/>
            <result column="order_number" property="orderNumber "/>
            <!--
                Configure the mapping relationship between the tb_user table and the entity class User private User user;
            -->
            <association property="user" javaType="User" autoMapping="true">
                <!-- Configure the mapping relationship between the tb_user table and the entity class User -->
                <id column="id" property="id"/>
            </association>
         </resultMap>

    2) One-to-many:
        <resultMap id="queryOneToManyResultMap" type="User" autoMapping="true">
            <!-- Configure the mapping relationship between tb_user table and User entity class -->
            <id column="id" property=" id"/>
            <!--
                TODO:
                1. The label used to configure one-to-many is collection
                2.Common attributes of collection tags: private List<Order> orderList;
                    1) property="orderList": Indicates the name of the collection container that stores multiple order objects
                    2) ofType="Order": The attribute value Order is a collection of multiple order containers that store List The generic type List<Order>
            -->
            <collection property="orderList" ofType="Order" autoMapping="true">
                <!-- Configure the mapping relationship between the tb_order table and the Order entity class -->
                <id column=" oid" property="id"/>
            </collection>
        </resultMap>
3. Annotation realizes addition, deletion, modification and query: ***************************
    @Select: query
    @Insert: insert
    @ Update: Update
    @Delete: Delete
4. Annotations to achieve self-incrementing primary key backfill:
    use annotations on the added method: @Options(useGeneratedKeys = true, keyColumn = "primary key field name", keyProperty = "primary key member variable name")

5. Annotate to implement dynamic sql:
@SelectProvider(type = tool class.class, method = "method name")

Guess you like

Origin blog.csdn.net/anyi2351033836/article/details/125365122