zoukankan      html  css  js  c++  java
  • Mybatis:入门

    helloworld(入门)

    建表语句

    CREATE TABLE `tbl_employee`  (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `last_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
      `gender` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
      `email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
      PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
    
    INSERT INTO `tbl_employee` VALUES (1, 'tom', '0', 'tom@qq.com');
    

    实体类:

    @Data
    @ToString
    public class Employee {
        private Integer id;
        private String lastName;
        private String email;
        private String gender;
    }
    

    pom.xml

            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.1</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.16</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.47</version>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13</version>
            </dependency>
    

    log4j.xml放在类路径下:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
    
    <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    
     <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
       <param name="Encoding" value="UTF-8" />
       <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m  (%F:%L) 
    " />
       </layout>
     </appender>
     <logger name="java.sql">
       <level value="debug" />
     </logger>
     <logger name="org.apache.ibatis">
       <level value="info" />
     </logger>
     <root>
       <level value="debug" />
       <appender-ref ref="STDOUT" />
     </root>
    </log4j:configuration>
    

    sql映射文件EmployeeMapper.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">
    <mapper namespace="com.wj.EmployeeMapper">
        <!--
        namespace:命名空间
        id:唯一标识
        resultType:返回值类型
        #{id}:从传递过来的参数中取出id值
        -->
        <select id="selectEmp" resultType="com.wj.bean.Employee">
            select
                id
                ,last_name as lastName
                ,email
                ,gender
            from
                tbl_employee
            where id = #{id}
        </select>
    </mapper>
    

    全局配置文件:

    <?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>
        <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://localhost:3306/mybatis"/>
                    <property name="username" value="root"/>
                    <property name="password" value="1234"/>
                </dataSource>
            </environment>
        </environments>
        <!--将我们写好的sql映射文件一定要注册在全局配置文件中-->
        <mappers>
            <mapper resource="EmployeeMapper.xml"/>
        </mappers>
    </configuration>
    

    编写测试类:

        @Test
        public void test() throws IOException {
            //1.根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //2.获取sqlSession实例,直接执行已经映射的sql语句
            SqlSession session = sqlSessionFactory.openSession();
            try {
                // sql的唯一标识 (namespace + id)    statement Unique identifier matching the statement to use.
                // 执行sql要用的参数 parameter A parameter object to pass to the statement.
                Employee employee = session.selectOne("com.wj.EmployeeMapper.selectEmp", 1);
                System.out.println(employee);
            } finally {
                session.close();
            }
        }
    

    执行结果:

    image-20210113202203978

    总结:

    • 根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象(包含数据源相关信息)

    • 编写sql映射文件,配置了每一个sql和sql的封装规则等

    • 将SQL的映射文件注册在全局配置文件中

    • 写代码

      • 根据全局配置文件获取SqlSessionFactory

      • 使用SqlSession工厂,获取sqlSession(一个sqlSession就是和数据库的一次会话,用完关闭)

      • 使用sql的唯一标识告诉Mybatis执行哪个sql。sql都是保存在Sql映射文件中的。

    项目结构:

    image-20210113203902773

    面向接口编程

    官方文档中:

    image-20210113202916205

    大意是说上一种方法是旧版本的写法,新版本中,可以使用接口的方式,使代码更加简介,可以避免类型转换等出错。

    创建一个接口:EmployeeMapper.java

    public interface EmployeeMapper {
        public Employee getEmpById(Integer id);
    }
    

    修改sql映射文件:

    <?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.wj.dao.EmployeeMapper">
        <!--
        namespace:命名空间 接口的全类名
        id:唯一标识
        resultType:返回值类型
        #{id}:从传递过来的参数中取出id值
        -->
        <select id="getEmpById" resultType="com.wj.bean.Employee">
            select
                id
                ,last_name as lastName
                ,email
                ,gender
            from
                tbl_employee
            where id = #{id}
        </select>
    </mapper>
    

    测试:

        @Test
        public void test01() throws IOException {
            //1.根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象
            SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
            SqlSession session = sqlSessionFactory.openSession();
            try {
                EmployeeMapper employeeMapper= session.getMapper(EmployeeMapper.class);
                Employee emp = employeeMapper.getEmpById(1);
                System.out.println(emp);
            } finally {
                session.close();
            }
        }
    
        private SqlSessionFactory getSqlSessionFactory() throws IOException {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            return new SqlSessionFactoryBuilder().build(inputStream);
        }
    

    执行结果:

    image-20210113203610000

    此时,我们发现,并没有为EmployeeMapper编写实现类,竟然也执行了方法,打断点,发现用的是代理类实现

    image-20210113203815217

  • 相关阅读:
    bzoj-2748 2748: [HAOI2012]音量调节(dp)
    bzoj-2338 2338: [HNOI2011]数矩形(计算几何)
    bzoj-3444 3444: 最后的晚餐(组合数学)
    codeforces 709E E. Centroids(树形dp)
    codeforces 709D D. Recover the String(构造)
    codeforces 709C C. Letters Cyclic Shift(贪心)
    codeforces 709B B. Checkpoints(水题)
    codeforces 709A A. Juicer(水题)
    Repeat Number
    hdu 1003 Max Sum (动态规划)
  • 原文地址:https://www.cnblogs.com/wwjj4811/p/14274335.html
Copyright © 2011-2022 走看看