Mybatis学习

Posted miantiao312

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis学习相关的知识,希望对你有一定的参考价值。

2、搭建Java工程

A、加入mybatis核心包、依赖包、数据驱动包

B、在classpath下创建log4j.properties和db.propertites(mybatis默认使用log4j作为输出日志信息)

log4j.properties

    # Global logging configuration
    log4j.rootLogger=DEBUG, stdout
    # Console output...
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

db.propertites

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
    jdbc.username=root
    jdbc.password=root

C、在classpath下创建SqlMapConfig.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>
        
        <!-- 配置别名 -->
        <typeAliases>
            <!--扫描包的形式创建别名,别名就是类名,不区分大小写 -->
            <package name="com.kid.mybatis.pojo"/>
        </typeAliases>
        
        <!-- 和spring整合后 environments配置将废除-->
        <environments default="development">
            <environment id="development">
                <!-- 使用jdbc事务管理-->
                <transactionManager type="JDBC"/>
                
                <!-- 数据库连接池-->
                <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>
        
        <!-- 加载mapper文件 -->
        <mappers>
            <!-- 使用扫描包的形式加载mapper文件 -->
            <package name="com.kid.mybatis.mapper"/>
        </mappers>
    </configuration>

D、pojo类

    public class Orders {
        private Integer id;
        private Integer userId;
        private String number;
        private Date createtime;
        private String note;
        private User user;

        //省略getter/setter方法
    }
    
    public class QueryVo {
        private User user;
        private List<Integer> ids;

        省略getter/setter方法
    }
    
    public class User {
        private Integer id;
        private String username;
        private String sex;
        private Date birthday;
        private String address;
    
        省略getter/setter方法
    }

3、输入映射和输出映射:resultType和resultMap的使用

    OrderMapper接口:
        public interface OrderMapper {
            List<Orders> getOrderList();
            List<Orders> getOrderListResultMap();
        }

    OrderMapper.xml:
        <mapper namespace="com.kid.mybatis.mapper.OrderMapper">

            <select id="getOrderList" resultType="orders">
                select id,user_id userId,number,createtime,note from orders
            </select>
            
            <!--使用resultMap; type:返回结果映射的pojo,可以使用别名-->
            <resultMap type="orders" id="order_list_result_map">
                <!--id主键的映射,property是pojo中主键的属性,column:返回结果中主键映射  -->
                <id property="id" column="id"/>
                <result property="userId" column="user_id"/>
                <result property="number" column="number"/>
                <result property="createtime" column="createtime"/>
                <result property="note" column="note"/>
            </resultMap>
            <select id="getOrderListResultMap" resultMap="order_list_result_map">
                select id,user_id,number,createtime,note from orders
            </select>
        </mapper>
    
    测试文件:OrderMapperTest
        public class OrderMapperTest {

            private SqlSessionFactory sqlSessionFactory = null;
            @Before
            public void init() throws Exception {
                //第一步:创建一个SQLSessionFactoryBuilder对象。
                SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
                //第二步:加载配置文件。
                InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
                //第三步:创建SQLSessionFactory对象
                sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
            }
            
            @Test
            public void getOrderList() {
                SqlSession sqlSession = sqlSessionFactory.openSession();
                OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
                
                List<Orders> orderList = orderMapper.getOrderList();
                for (Orders orders : orderList) {
                    System.out.println(orders);
                }
                sqlSession.close();
            }
            
            @Test
            public void getOrderListResultMap() {
                SqlSession sqlSession = sqlSessionFactory.openSession();
                OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
                
                List<Orders> orderList = orderMapper.getOrderList();
                for (Orders orders : orderList) {
                    System.out.println(orders);
                }
                sqlSession.close();
            }
        }

这一块主要讲输入和输出映射无法匹配的问题!我们的 Order 中是userId,数据库中的字段名称是 user_id,这块我们使用了2种方法查询:

A、别名查询  select id,user_id userId,number,createtime,note from orders
B、使用 requltMap ,type:返回结果映射的pojo,可以使用别名(详细看上面注释)
   
   resultMap标签简单介绍:
        <id />:此属性表示查询结果集的唯一标识,非常重要。如果是多个字段为复合唯一约束则定义多个<id />。
        Property:表示User类的属性。
        Column:表示sql查询出来的字段名。
        Column 和 property放在一块儿表示将sql查询出来的字段映射到指定的pojo类属性上。
        <result />:普通结果,即pojo的属性。

4、动态SQL语句

   UserMapper接口:
        public interface UserMapper {
            User getUserByQueryVo(QueryVo queryVo);
            int findUserCount();
            List<User> findUserList(User user);
            List<User> findUseListByIds(QueryVo queryVo);
        }

    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">
        
        <mapper namespace="com.kid.mybatis.mapper.UserMapper">
            <!-- 通过queryVo查询客户 -->
            <select id="getUserByQueryVo" parameterType="queryvo" resultType="user">
                select * from user where id = #{user.id}
            </select>
            
            <!-- 查询用户总数 -->
            <select id="findUserCount" resultType="int">
                select count(*) from user 
            </select>
            
            <!-- ############################# 华丽的 分割线 ################################# -->
            <!-- SQL片段引用&传递pojo综合查询用户信息 -->
            <sql id="find_user_list_where">
                <where>
                    <if test="id != null">
                        and id =#{id}
                    </if>
                    <if test="username != null and username != ‘‘ ">
                        and username like ‘%${username}%‘
                    </if>
                </where>
            </sql>
            <select id="findUserList" parameterType="user" resultType="user">
                select * from user
                <include refid="find_user_list_where"/>
            </select>
            
            <!-- ############################# 华丽的 分割线 ################################# -->
            <!-- SQL片段 & 动态sql foreach语句 -->
            <sql id="user_field_list">
                id,username,birthday,sex,address
            </sql>
            <select id="findUseListByIds" parameterType="queryvo" resultType="user">
                select <include refid="user_field_list"/> 
                    from user
                <where>
                    <foreach collection="ids" item="id" open="and id in(" close=")" separator=",">
                        #{id}
                    </foreach>
                </where>
            </select>
        </mapper>

    测试文件 UserMapperTest:
        public class UserMapperTest {

            private SqlSessionFactory sqlSessionFactory = null;
            @Before
            public void init() throws Exception {
                //第一步:创建一个SQLSessionFactoryBuilder对象。
                SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
                //第二步:加载配置文件。
                InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
                //第三步:创建SQLSessionFactory对象
                sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
            }
            
            @Test
            public void findUserByQueryVoTest() {
                SqlSession sqlSession = sqlSessionFactory.openSession();
                //获取mapper的代理对象
                UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
                //创建QueryVo对象
                QueryVo queryVo=new QueryVo();
                //创建User对象
                User user=new User();
                user.setId(10);
                queryVo.setUser(user);
                //根据queryvo查询客户
                User u  = userMapper.getUserByQueryVo(queryVo);
                System.out.println(u);
                sqlSession.close();
            }
            
            @Test
            public void findUserCountTest() {
                SqlSession sqlSession = sqlSessionFactory.openSession();
                UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
                
                int count = userMapper.findUserCount();
                sqlSession.close();
                System.out.println(count);
            }
            
            @Test   //动态Sql测试 
            public void findUserListTest() {
                SqlSession sqlSession = sqlSessionFactory.openSession();
                UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
                
                User user=new User();
                user.setId(10);
                user.setUsername("张");
                List<User> userList = userMapper.findUserList(user);
            
                //循环遍历
                for (User user2 : userList) {
                    System.out.println(user2);
                }
                sqlSession.close();
            }
            
            @Test   //动态Sql测试 
            public void findUseListByIdsTest() {
                SqlSession sqlSession = sqlSessionFactory.openSession();
                UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
                QueryVo queryVo=new QueryVo();
                List<Integer> ids = new ArrayList<>();
                ids.add(1);//查询id为1的用户
                ids.add(10); //查询id为10的用户
                queryVo.setIds(ids);
                
                List<User> userList = userMapper.findUseListByIds(queryVo);
            
                //循环遍历
                for (User user2 : userList) {
                    System.out.println(user2);
                }
                sqlSession.close();
            }               
        }
    

项目结构图

技术分享图片

以上是关于Mybatis学习的主要内容,如果未能解决你的问题,请参考以下文章

markdown [mybatis参考]关于mybatis #mybatis的一些片段

Mybatis 学习笔记总结

Mybatis学习笔记:动态SQL

SSM-MyBatis-05:Mybatis中别名,sql片段和模糊查询加getMapper

mybatis动态sql片段与分页,排序,传参的使用

MyBatis动态SQL标签用法