mybatis

作者: 鱼落于天 | 来源:发表于2020-11-22 22:21 被阅读0次

    mybaits

    官方入门传送门

    一、 使用前置环境

    • pom.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>wen.tai</groupId>
        <artifactId>java-mabits</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <maven.compiler.source>15</maven.compiler.source>
            <maven.compiler.target>15</maven.compiler.target>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.4</version>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.45</version>
            </dependency>
    
    
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.12</version>
            </dependency>
    
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
            </dependency>
        </dependencies>
    </project>
    
    • 数据库
      • 一个人有个事迹 【一对多】
      • 一个事迹属于一个人 【一对一】
      • 一个人有多个角色,一个角色属于多个人 【多对多】
    # 个人事迹表
    CREATE TABLE `deeds` (
         `id` int(11) NOT NULL AUTO_INCREMENT,
         `uid` int(10) unsigned NOT NULL,
         `deed` varchar(11) NOT NULL,
         `created_at` datetime DEFAULT NULL COMMENT '创建时间',
         PRIMARY KEY (`id`)
       ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4;
       INSERT INTO `homestead`.`deeds` (`id`, `uid`, `deed`, `created_at`) VALUES ('1', '1', '虎牢关战三英', '2020-11-22 02:16:40');
       INSERT INTO `homestead`.`deeds` (`id`, `uid`, `deed`, `created_at`) VALUES ('2', '5', '温酒斩华雄', '2020-11-22 02:21:45');
       INSERT INTO `homestead`.`deeds` (`id`, `uid`, `deed`, `created_at`) VALUES ('3', '4', '胡笳十八拍', '2020-11-22 02:22:14');
       INSERT INTO `homestead`.`deeds` (`id`, `uid`, `deed`, `created_at`) VALUES ('4', '5', '过五关斩六将', '2020-11-22 02:22:16');
       INSERT INTO `homestead`.`deeds` (`id`, `uid`, `deed`, `created_at`) VALUES ('5', '5', '刮骨疗毒', '2020-11-22 02:22:14');
       INSERT INTO `homestead`.`deeds` (`id`, `uid`, `deed`, `created_at`) VALUES ('6', '5', '桃园结义', '2020-11-22 02:22:14');
    
    CREATE TABLE `role` (
     `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
     `name` varchar(50) DEFAULT NULL,
     `desc` varchar(255) DEFAULT NULL,
     PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
    INSERT INTO `homestead`.`role` (`id`, `name`, `desc`) VALUES ('1', '武将', '三国武将');
    INSERT INTO `homestead`.`role` (`id`, `name`, `desc`) VALUES ('2', '侯爷', '有爵位的人');
    INSERT INTO `homestead`.`role` (`id`, `name`, `desc`) VALUES ('3', '女官', '女性官员');
    INSERT INTO `homestead`.`role` (`id`, `name`, `desc`) VALUES ('4', '艺术家', '文艺大家');
    
    
    CREATE TABLE `user` (
     `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
     `username` varchar(50) NOT NULL,
     `age` tinyint(1) unsigned NOT NULL DEFAULT '0',
     `sex` char(1) NOT NULL DEFAULT '男',
     `created_at` date DEFAULT NULL COMMENT '添加时间',
     PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4;
    INSERT INTO `homestead`.`user` (`id`, `username`, `age`, `sex`, `created_at`) VALUES ('1', '高柔', '89', '男', '2020-11-22');
    INSERT INTO `homestead`.`user` (`id`, `username`, `age`, `sex`, `created_at`) VALUES ('2', '吕布', '37', '男', '2020-11-22');
    INSERT INTO `homestead`.`user` (`id`, `username`, `age`, `sex`, `created_at`) VALUES ('3', '貂蝉', '27', '女', '2020-11-22');
    INSERT INTO `homestead`.`user` (`id`, `username`, `age`, `sex`, `created_at`) VALUES ('4', '蔡文姬', '45', '女', '2020-11-22');
    INSERT INTO `homestead`.`user` (`id`, `username`, `age`, `sex`, `created_at`) VALUES ('5', '关羽', '68', '男', '2020-11-22');
    
    CREATE TABLE `user_role` (
     `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
     `rid` int(11) DEFAULT '0' COMMENT '角色id',
     `uid` int(11) DEFAULT NULL COMMENT '用户id',
     PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4;
    INSERT INTO `homestead`.`user_role` (`id`, `rid`, `uid`) VALUES ('1', '1', '1');
    INSERT INTO `homestead`.`user_role` (`id`, `rid`, `uid`) VALUES ('2', '2', '1');
    INSERT INTO `homestead`.`user_role` (`id`, `rid`, `uid`) VALUES ('3', '3', '4');
    INSERT INTO `homestead`.`user_role` (`id`, `rid`, `uid`) VALUES ('4', '4', '4');
    INSERT INTO `homestead`.`user_role` (`id`, `rid`, `uid`) VALUES ('5', '1', '5');
    INSERT INTO `homestead`.`user_role` (`id`, `rid`, `uid`) VALUES ('6', '2', '5');
    
    

    二、实现过程

    三、配置文件详解

    1. mapper

    2. mybatis配置文件配置

    • 标签
    • 连接池配置
    • 在mybatis配置文件中,配置 environment 标签时,datasource标签type属性有三个值,分别是
      • POOLED: 使用连接池,数据库链接使用后回返回池
      • UNPOOLED: 不适用连接池,每次链接都是重新连接
      • JNDI: 基于服务器环境
        1. Tomcat时,必须启动服务才能使用
    • mapper.xml中重复使用的sql
    <sql id="fromUser">
        select * from user
    </sql>
    
    <!-- 使用时,使用标签进行 替换 -->
     <include refid="fromUser"/>
    
    • 多个参数mapper.xml写法
    public class IUserMapper { 
         /**
         * 多个参数查询条件 方案一: 使用占位符
         * 对应mapper。xml: select * from user where username = #{arg0} and sex = #{arg1}
         *
         * @param name 姓名
         * @param sex  性别
         * @return
         */
        List<User> find(String name, char sex);
    
        /**
         * 多个参数查询条件 方案二: 使用注解
         * 对应mapper。xml: select * from user where username = #{userName, jdbcType=VARCHAR} and id = #{myId, jdbcType=INTEGER}
         *
         * @param name 姓名
         * @param sex  性别
         * @return
         */
        List<User> findByNameAndId(@Param("userName") String name, @Param("myId") int id);
    
        /**
         * 多个参数查询条件 方案三:Map
         * 对应mapper。xml: select * from user where username = #{userName, jdbcType=VARCHAR} and id = #{myId, jdbcType=INTEGER}
         * @param paramMap 参数
         *                 paramMap.put(“userName”,”对应具体的参数值”);
         *                 paramMap.put(“myId”,”对应具体的参数值”);
         * @return
         */
        List<User> findByParamMap(Map<String, Object> paramMap);
    
        /**
         * 多个参数查询条件 方案四: 利用OGNL,通过传入对象的属性进行获取参数
         * 对应mapper。xml: select * from user where username = #{userName} and id = #{id}
         * @param user
         * @return
         */
        User findByUser(User user);
    }
    
    • insert 方法返回自增id
    <insert id="insert" parameterType="wen.tai.domain.User">
            <!--         获取插入的id keyProperty-->
            <selectKey keyProperty="id" order="AFTER" keyColumn="id" resultType="int">
                select last_insert_id();
            </selectKey>
    
            insert into user (username, age, sex, created_at) value (#{username}, #{age}, #{sex}, #{createdAt});
    </insert>
    

    四、使用过程

    • 基本使用
    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 wen.tai.dao.IUserDao;
    import wen.tai.domain.User;
    import java.io.InputStream;
    
    public class MybatisTest {
    
    
        public static void main(String[] args) throws Exception {
            InputStream in = Resources.getResourceAsStream("mybatisConfig.xml");
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            SqlSessionFactory build = sqlSessionFactoryBuilder.build(in);
            SqlSession sqlSession = build.openSession();
    
            IUserDao dao = sqlSession.getMapper(IUserDao.class);
            List<User> all = dao.findAll();
    
            for (User user : all) {
                System.out.println(user);
            }
    
            in.close();
            sqlSession.close();
        }
    }
    

    六、注解开发

    七、 其他说明

    • 一级缓存
    • 二级缓存

    未完待续、今天有点晚了。

    相关文章

      网友评论

          本文标题:mybatis

          本文链接:https://www.haomeiwen.com/subject/wwmpiktx.html