美文网首页
1.mybatis入门

1.mybatis入门

作者: YNZXGWZM | 来源:发表于2019-08-08 18:10 被阅读0次
    • 目录结构


      image.png
    • 准备pom.xml文件
    
    <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>com.mc</groupId>
      <artifactId>mcMybatis</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>war</packaging>
    
      <properties>
        <java.version>1.6</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
          <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.3.0</version>
        </dependency>
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.38</version>
        </dependency>
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>1.7.12</version>
        </dependency>
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>1.7.12</version>
        </dependency>
        <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.17</version>
        </dependency>
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
              <source>${java.version}</source>
              <target>${java.version}</target>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>
    
    • 创建mybatis-config .xml
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <settings>
            <setting name="logImpl" value="LOG4J"/>
        </settings>
        
         <typeAliases>
            <package name="com.mc.model"/>
        </typeAliases>
    
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC">
                    <property name="" value=""/>
                </transactionManager>
                <dataSource type="UNPOOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://***.**.**.146:3306/test"/>
                    <property name="username" value="root"/>
                    <property name="password" value="fumengchao"/>
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <!--<mapper resource="com/mc/mapper/CountryMapper.xml"/>-->
            <package name="com.mc.mapper"/>
        </mappers>
    </configuration>
    

    简单介绍下这个配置:

    1. <setting name="logImpl" value="LOG4J"/>中的logImpl属性指定使用log4j输出日志。
    2. <typeAliases>设置一个包的别名别名,配置过后在具体的xml中可以只写类名就可以。
    3. <environments>环境 配置中 主要 配置了数据库连接。
    4. </mappers>中可以配置具体的mapper路径(通过resource),也可以通过包来配置(package)
    
    import java.io.Serializable;
    import java.util.Date;
    import java.util.List;
    
    /**
     * 用户表
     */
    public class SysUser implements Serializable {
        private static final long serialVersionUID = -328602757171077630L;
        /**
         * 用户ID
         */
        private Long id;
        /**
         * 用户名
         */
        private String userName;
    }
    
    • 在src/main/resources下添加log4j.properies,<mapper namespace="com.mc.mapper.UserMapper">
    log4j.rootLogger=ERROR, stdout
    
    #MyBatis \u65E5\u5FD7\u914D\u7F6E
    注意此包名必须和namesapce下面的包名一致
    log4j.logger.com.mc.mapper=TRACE
    
    ##\u5168\u5C40\u914D\u7F6E
    log4j.rootLogger=ERROR, stdout
    
    #MyBatis \u65E5\u5FD7\u914D\u7F6E
    #注意此包名必须和namesapce下面的包名一致
    log4j.logger.com.mc.mapper=TRACE
    
    #\u63A7\u5236\u53F0\u8F93\u51FA\u914D\u7F6E
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
    
    • 创建userMapper.java
    public interface UserMapper {
    
        SysUser selectById(Long id);
    
        List<SysUser> selectAll();
    
        /**
         * 通过用户ID查询角色
         * @param userId
         * @return
         */
        List<SysRoleExtend> selectRolesByUserId(Long userId);
    }
    
    • 创建userMapper.xml
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    <mapper namespace="com.mc.mapper.UserMapper">
        <resultMap id="userMap" type="SysUser">
            <id property="id" column="id"/>
            <result property="userName" column="user_name"/>
            <result property="userPassword" column="user_password"/>
            <result property="userEmail" column="user_email"/>
            <result property="userInfo" column="user_info"/>
            <result property="headImg" column="head_img" jdbcType="BLOB"/>
            <result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
        </resultMap>
        <select id="selectById" resultMap="userMap">
            select * from sys_user where id=#{id}
        </select>
    
        <select id="selectAll" resultType="SysUser">
            select * from sys_user
        </select>
    
        <!--方式1:在sysRole中增加一个SysUser类,通过类名.字段名的方式拿到-->
    
        <!--<select id="selectRolesByUserId" resultType="SysRole">-->
            <!--SELECT-->
              <!--a.id,-->
              <!--a.role_name roleName,-->
              <!--a.enabled,-->
              <!--a.create_by createBy,-->
              <!--a.create_time createTime,-->
              <!--c.user_name as "user.userName",-->
              <!--c.id as "user.id"-->
            <!--FROM-->
              <!--sys_user_role b-->
            <!--INNER JOIN sys_role a ON a.id = b.role_id-->
            <!--INNER JOIN sys_user c ON c.id = b.user_id-->
            <!--WHERE c.id=#{userId}-->
        <!--</select>-->
        <!--方式2:写一个类继承SysRole 扩展里面的字段要和数据库保持一致-->
        <select id="selectRolesByUserId" resultType="SysRoleExtend">
            SELECT
              a.id,
              a.role_name roleName,
              a.enabled,
              a.create_by createBy,
              a.create_time createTime,
              c.user_name userName,
              c.id as userId
    
            FROM
              sys_user_role b
            INNER JOIN sys_role a ON a.id = b.role_id
            INNER JOIN sys_user c ON c.id = b.user_id
            WHERE c.id=#{userId}
        </select>
    
    </mapper>```
    - 让mybatis跑起来(必须和xml路径一致,xml创建包的时候必须一层一层创建,不然会有问题)
    ```/***
     * @ClassName BaseMapperTest
     * @Description todo
     * @Author CC
     * @Date: 2019/8/714:01
     * @Version 1.0
     */
    public class BaseMapperTest {
        private static SqlSessionFactory sqlSessionFactory;
    
        @BeforeClass
        public static void init() {
            try {
                Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
                reader.close();
            } catch (IOException ignore) {
                ignore.printStackTrace();
            }
        }
    
        public SqlSession getSqlSession() {
            return sqlSessionFactory.openSession();
        }
    }
    
     * @ClassName UserMapperTest
     * @Description todo
     * @Author CC
     * @Date: 2019/8/714:09
     * @Version 1.0
     */
    public class UserMapperTest extends BaseMapperTest {
    
        @Test
        public void testSelectById() {
            SqlSession sqlSession = getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            SysUser sysUser = mapper.selectById(1L);
            Assert.assertNotNull(sysUser);
        }
    
        @Test
        public void testSelectAll() {
            SqlSession sqlSession = getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<SysUser> sysUsers = mapper.selectAll();
            Assert.assertNotNull(sysUsers);
            sqlSession.close();
        }
    
        @Test
        public void testSelectRolesByUserId() {
            SqlSession sqlSession = getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<SysRoleExtend> sysRoles = mapper.selectRolesByUserId(1L);
            Assert.assertNotNull(sysRoles);
            sqlSession.close();
        }
    }
    

    相关文章

      网友评论

          本文标题:1.mybatis入门

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