mybatis

介紹

概述
    MyBatis最早源自Apache基金會(huì)的一個(gè)開(kāi)源項(xiàng)目iBatis.
    2010年這個(gè)項(xiàng)目由Apache software foundation遷移到google code,并且改名為MyBatis;
    MyBatis是支持普通SQL查詢(xún),存儲(chǔ)程和高級(jí)映射的優(yōu)秀持久層框架汽畴。
    MyBati封裝了幾乎所有的JDBC代碼和參數(shù)的手工設(shè)置以及結(jié)果集的檢索;
    MyBatist使用簡(jiǎn)單的XML或注解做配置和定義映射關(guān)系將Java的POJOs(Plain Old Java Objects)映射成數(shù)據(jù)庫(kù)中的記錄.
下載
    http://www.mybatis.org/mybatis-3/
Mybatis體系結(jié)構(gòu)
    1.加載配置:配置來(lái)源于兩個(gè)地方预柒,一處是配置文件,一處是Java代碼的注解喳资,將SQL的配置信息加載成為一個(gè)個(gè)MappedStatement對(duì)象(包括了傳入?yún)?shù)映射配置挽拂、執(zhí)行的SQL語(yǔ)句、結(jié)果映射配置)骨饿,存儲(chǔ)在內(nèi)存中亏栈。
    2.SQL解析:當(dāng)API接口層接收到調(diào)用請(qǐng)求時(shí),會(huì)接收到傳入SQL的ID和傳入對(duì)象(可以是Map宏赘、JavaBean或者基本數(shù)據(jù)類(lèi)型)绒北,Mybatis會(huì)根據(jù)SQL的ID找到對(duì)應(yīng)的MappedStatement,然后根據(jù)傳入?yún)?shù)對(duì)象對(duì)MappedStatement進(jìn)行解析察署,解析后可以得到最終要執(zhí)行的SQL語(yǔ)句和參數(shù)闷游。
    3.SQL執(zhí)行:將最終得到的SQL和參數(shù)拿到數(shù)據(jù)庫(kù)進(jìn)行執(zhí)行,得到操作數(shù)據(jù)庫(kù)的結(jié)果。
    4.結(jié)果映射:將操作數(shù)據(jù)庫(kù)的結(jié)果按照映射的配置進(jìn)行轉(zhuǎn)換脐往,可以轉(zhuǎn)換成HashMap休吠、JavaBean或者基本數(shù)據(jù)類(lèi)型,并將最終結(jié)果返回业簿。
MyBatis配置文件
    MyBatis框架的XML配置文件包含下面兩種類(lèi)型
        1.mybatis-config.xml (1個(gè))
            主配置文件瘤礁,用于指定數(shù)據(jù)庫(kù)連接參數(shù)和框架參數(shù)
            在mybatis官網(wǎng)查看http://www.mybatis.org/mybatis-3/getting-started.html
        2.DepartmentMapper.xml (n個(gè))
            映射定義文件,用于定義SQL語(yǔ)句和映射信息
            在mybatis官網(wǎng)查看http://www.mybatis.org/mybatis-3/sqlmap-xml.html
框架API簡(jiǎn)介 
    SqlSessionFactoryBuilder
        該對(duì)象負(fù)責(zé)根據(jù)MyBatis配置文件mybatis-config.xml構(gòu)建SqISessionFaciory實(shí)例
    SqlSessionFactory
        每一個(gè)MyBatis的應(yīng)用程序都以一個(gè)SqISessionFactory對(duì)象為核心梅尤。該對(duì)象負(fù)責(zé)創(chuàng)建SqlSession對(duì)象實(shí)例
    SqlSession
        該對(duì)像包含了所有執(zhí)行SQL操作的方法柜思,用于執(zhí)行己映射的SQL語(yǔ)句
使用步驟
    1.為工程添加MyBatis開(kāi)發(fā)包( mybatis-x.x.x.jar )和數(shù)據(jù)庫(kù)驅(qū)動(dòng)包
    2.在src下添加MyBatis配置文件SqIMapConfig.xml
    3.修改SqIMapConfig.xml指定數(shù)據(jù)庫(kù)連接參數(shù)
    4.利用MyBatis API編程,獲取SqISession實(shí)例

mybatis

第一種方式步驟
    1.maven引入依賴(lài)包
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
        </dependency>
    2.創(chuàng)建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>
          <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/test"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
              </dataSource>
            </environment>
          </environments>
          <mappers>
            <mapper resource="com/shuai/mybatis/domain/User.xml"/>
          </mappers>
        </configuration>
    3.創(chuàng)建數(shù)據(jù)庫(kù)表/創(chuàng)建實(shí)體類(lèi)
        public class User {
            private int id;
            private String name;
            private int age;
        }
    4.創(chuàng)建實(shí)體類(lèi)配置文件(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.shuai.mybatis.domain.User">
            <insert id="insert" parameterType="com.shuai.mybatis.domain.User">
                insert into user (id,name,age) values (#{id},#{name},#{age})
            </insert>
        </mapper>
    5.測(cè)試
        public void test() throws Exception{
            String resource = "mybatis-config.xml";
            Reader reader = Resources.getResourceAsReader(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            User user = new User();
            user.setName("xxx");
            user.setAge(10);
            sqlSession.insert(User.class.getName()+".insert",user);
            sqlSession.commit();
            sqlSession.close();
        }
第二種方式步驟
    1.maven引入依賴(lài)包
    2.創(chuàng)建mybatis-config.xml
    3.創(chuàng)建數(shù)據(jù)庫(kù)表/創(chuàng)建實(shí)體類(lèi)
    4.創(chuàng)建實(shí)體類(lèi)Mapper接口
        public interface UserDao {
            public void insert(User user);
        }
    5.創(chuàng)建實(shí)體類(lèi)配置文件(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.shuai.mybatis.dao.UserDao">
            <insert id="insert" parameterType="com.shuai.mybatis.domain.User">
                insert into user (id,name,age) values (#{id},#{name},#{age})
            </insert>
        </mapper>
    6.測(cè)試
        public void test() throws Exception{
            String resource = "mybatis-config.xml";
            Reader reader = Resources.getResourceAsReader(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            User user = new User();
            user.setName("xxx");
            user.setAge(10);
            UserDao mapper = sqlSession.getMapper(UserDao.class);
            mapper.insert(user);
            sqlSession.commit();
            sqlSession.close();
        }

加載配置文件

mybatis-config.xml
    <configuration>
        <properties resource="conn.properties" />
    </configuration>

增刪改查/分頁(yè)查詢(xún)

注意:增加/刪除/修改 都可以使用update方法?
增加
    <insert id="insert" parameterType="com.shuai.mybatis.domain.User">
        insert into user (id,name,age) values (#{id},#{name},#{age})
    </insert>
    sqlSession.insert(User.class.getName()+".insert",user);
    增加時(shí)返回id
    <insert id="insert" parameterType="Teacher" useGeneratedKeys="true" keyProperty="id">
        insert into teacher (name,age) values(#{name},#{age})
    </insert>
    Teacher teacher = new Teacher();
    teacher.setName("shuaige");
    teacher.setAge(20);
    sqlSession.insert(Teacher.class.getName()+".insert", teacher);
    System.out.println(teacher.getId());
    注意:
        useGeneratedKeys="true" 設(shè)置是否使用JDBC的getGenereatedKeys方法獲取主鍵并賦值到keyProperty設(shè)置的主鍵字段中
        keyProperty="id"  指定JavaBean的主鍵字段
刪除
    <delete id="delete" parameterType="com.shuai.mybatis.domain.User">
        delete from user where id=#{id}
    </delete>
    sqlSession.delete(User.class.getName()+".delete",user);
    <delete id="delete" parameterType="int">
        delete from user where id=#{id}
    </delete>
    sqlSession.delete(User.class.getName()+".delete",7);
修改
    <update id="update" parameterType="com.shuai.mybatis.domain.User">
        update user set name=#{name},age=#{age} where id=#{id}
    </update>
    sqlSession.update(User.class.getName()+".update",user);
查詢(xún)
    根據(jù)id查詢(xún)
        <select id="getById" parameterType="int" resultType="com.shuai.mybatis.domain.User">
            select * from user where id=#{id}
        </select>
        User user = sqlSession.selectOne(User.class.getName()+".getById", 8);
    根據(jù)名字模糊查詢(xún)
        <select id="getByName" parameterType="java.lang.String" resultType="com.shuai.mybatis.domain.User">
            select * from user where name like #{name}
        </select>
        List<User> list = sqlSession.selectList(User.class.getName()+".getByName", "%shuaige%");
    分頁(yè)查詢(xún)
        <select id="getByPage" parameterType="java.util.Map" resultType="com.shuai.mybatis.domain.User">
            select * from user where name like #{name} limit #{start},#{size}
        </select>
        Map<String,Object> dataMap = new HashMap<String,Object>();
        dataMap.put("name", "%shuaige%");
        dataMap.put("start", 0);
        dataMap.put("size", 3);
        List<User> list = sqlSession.selectList(User.class.getName()+".getByPage", dataMap);
        第二種
            <select id="getLimit" resultType="User">
                select * from user limit #{offset},#{limit} //注意:這里必須要這樣寫(xiě)
            </select>
            RowBounds bounds = new RowBounds(0,5);
            List<User> list = sqlSession.selectList(User.class.getName()+".getLimit", bounds);

別名配置

在主配置文件中定義類(lèi)的別名
    <typeAliases>
        <typeAlias type="com.shuai.mybatis.domain.User" alias="User"/>
    </typeAliases>
映射文件中的resultType和parameterType就可以改為使用別名了
    <select id="getByPage" parameterType="java.util.Map" resultType="User"></select>
    <insert id="insert" parameterType="User"></insert>
注意:不區(qū)分大小寫(xiě)

定義結(jié)果集

在映射文件中定義結(jié)果集
    <resultMap type="User" id="userMap">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="age" property="age"/>
    </resultMap>
在映射文件中使用結(jié)果集
    <select id="getByPage" parameterType="java.util.Map" resultMap="userMap">
        select * from user where name like #{name} limit #{start},#{size}
    </select>
測(cè)試
    Map<String,Object> dataMap = new HashMap<String,Object>();
    dataMap.put("name", "%shuaige%");
    dataMap.put("start", 3);
    dataMap.put("size", 3);
    List<User> list = sqlSession.selectList(User.class.getName()+".getByPage", dataMap);
注意:
    重點(diǎn)在配置關(guān)聯(lián)映射的時(shí)候使用

動(dòng)態(tài)SQL(增刪改查/分頁(yè)查詢(xún))

總結(jié)
    sql/trim/if/foreach/where/set/choose/when/otherwise
注意:
    > 換為 &gt;
    < 換為 &lt;
增加
    <sql id="param">
        <trim suffixOverrides=",">
            <if test="name!=null">
                name,
            </if>
            <if test="age!=null">
                age,
            </if>
            <if test="birth!=null">
                birth,
            </if>
        </trim>
    </sql>
    <sql id="value">
        <trim suffixOverrides=",">
            <if test="name!=null">
                #{name},
            </if>
            <if test="age!=null">
                #{age},
            </if>
            <if test="birth!=null">
                #{birth},
            </if>
        </trim>
    </sql>
    <insert id="dinsert" parameterType="User">
        insert into user (<include refid="param"/>) values (<include refid="value"/>)
    </insert>
    public static void test() throws Exception{
        String resource = "mybatis-config.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = new User();
        user.setName("shuaige");
        sqlSession.update(User.class.getName()+".dinsert", user);
        sqlSession.commit();
        sqlSession.close();
    }
修改
    <update id="dupdate" parameterType="User">
        update user
        <set>
            <if test="name!=null">
                name=#{name},
            </if>
            <if test="age!=null">
                age=#{age},
            </if>
            <if test="birth!=null">
                birth=#{birth}
            </if>
        </set>
        where id=#{id}
    </update>
    public static void test5() throws Exception{
        String resource = "mybatis-config.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = new User();
        user.setId(23);
        user.setName("shuaige35");
        user.setAge(35);
        user.setBirth(new Date());
        sqlSession.update(User.class.getName()+".dupdate", user);
        sqlSession.commit();
        sqlSession.close();
    }
刪除
    <delete id="ddelete">
        delete from user where id in
        <foreach collection="array" open="(" close=")" separator="," item="ids">
            #{ids}
        </foreach>
    </delete>
    public static void test() throws Exception{
        String resource = "mybatis-config.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        int[] arr = new int[]{1,2,3};
        sqlSession.delete(User.class.getName()+".ddelete", arr);
        sqlSession.commit();
        sqlSession.close();
    }
查詢(xún)
    <select id="dget" parameterType="java.util.Map" resultMap="userMap">
        select * from user
        <where>
            <if test="id!=null">
                and id=#{id}
            </if>
            <if test="name!=null">
                and name like #{name}
            </if>
            <if test="age!=null">
                and age &gt; #{age}
            </if>
        </where>
    </select>
    public static void test() throws Exception{
        String resource = "mybatis-config.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Map<String,Object> dataMap = new HashMap<String,Object>();
        dataMap.put("name", "%shuaige%");
        dataMap.put("age", 30);
        List<User> list = sqlSession.selectList(User.class.getName()+".dget", dataMap);
        sqlSession.commit();
        sqlSession.close();
    }
    <select id="dgetIds" resultMap="userMap">
        select * from user where id in
        <foreach collection="list" open="(" close=")" separator="," item="ids">
            #{ids}
        </foreach>
    </select>
    public static void test() throws Exception{
        String resource = "mybatis-config.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<Integer> list = new ArrayList<Integer>();
        list.add(4);
        list.add(5);
        list.add(6);
        List<User> list2 = sqlSession.selectList(User.class.getName()+".dgetIds", list);
        sqlSession.commit();
        sqlSession.close();
    }

關(guān)聯(lián)操作

雙向關(guān)聯(lián)(多對(duì)多)
    sql:
        create table teacher(
            id int primary key auto_increment,
            name varchar(20),
            age int
        );
        create table student(
            id int primary key auto_increment,
            name varchar(20),
            age int
        );
        create table tea_stu(
            id int primary key auto_increment,
            t_id int,
            s_id int,
            constraint fk_teacher_id foreign key(t_id) references teacher(id),
            constraint fk_student_id foreign key(s_id) references student(id)
        );
    配置
        Teacher.xml
            <resultMap type="Teacher" id="teacherBaseMap">
                <id column="id" property="id"/>
                <result column="name" property="name"/>
                <result column="age" property="age"/>
            </resultMap>
            <resultMap type="Teacher" id="teacherMap">
                <collection property="students" resultMap="com.shuai.mybatis.domain.Student.studentBaseMap"></collection>
            </resultMap>
            <select id="getAll" resultMap="teacherMap">
                select * from teacher t inner join tea_stu ts on t.id=ts.t_id 
                inner join student s on ts.s_id=s.id
            </select>
            <insert id="insert" parameterType="Teacher" useGeneratedKeys="true" keyProperty="id">
                insert into teacher (name,age) values(#{name},#{age})
            </insert>
        Student.xml
            <resultMap type="Student" id="studentBaseMap">
                <id column="id" property="id"/>
                <result column="name" property="name"/>
                <result column="age" property="age"/>
            </resultMap>
            <resultMap type="Student" id="studentMap">
                <collection property="teachers" resultMap="com.shuai.mybatis.domain.Teacher.teacherBaseMap"></collection>
            </resultMap>
            <select id="getAll" resultMap="studentMap">
                select * from student s inner join tea_stu ts on s.id=ts.s_id 
                inner join teacher t on ts.t_id=t.id
            </select>
            <insert id="insert" parameterType="Student" useGeneratedKeys="true" keyProperty="id">
                insert into student (name,age) values(#{name},#{age})
            </insert>
    代碼
        插入
            Teacher teacher = new Teacher();
            teacher.setName("帥哥");
            Student student = new Student();
            student.setName("小明");
            teacher.getStudents().add(student);
            Student student1 = new Student();
            student1.setName("小明1");
            teacher.getStudents().add(student1);
            sqlSession.insert(Teacher.class.getName()+".insert", teacher);
            for(Student stu : teacher.getStudents()){
                TeaStu ts = new TeaStu();
                ts.setStudent(stu);
                ts.setTeacher(teacher);
                sqlSession.insert(Student.class.getName()+".insert", stu);
                sqlSession.insert(TeaStu.class.getName()+".insert", ts);
            }
        查詢(xún)
            List<Student> selectList = sqlSession.selectList(Student.class.getName()+".getAll", 1);
            List<Teacher> selectList1 = sqlSession.selectList(Teacher.class.getName()+".getAll", 1);
雙向關(guān)聯(lián)(一對(duì)多)
    sql:
        create table teacher(
            id int primary key auto_increment,
            name varchar(20),
            age int
        );
        create table student(
            id int primary key auto_increment,
            name varchar(20),
            age int,
            t_id int,
            constraint fk_tea_id foreign key(tid) references teacher(id)
        );
    配置
        <insert id="insert" parameterType="Teacher" useGeneratedKeys="true" keyProperty="id">
            insert into teacher (name,age) values(#{name},#{age})
        </insert>
        <insert id="insert" parameterType="Student" useGeneratedKeys="true" keyProperty="id">
            insert into student (name,age,t_id) values(#{name},#{age},#{teacher.id})
        </insert>
    代碼
        插入
            Teacher teacher = new Teacher();
        teacher.setName("帥哥");
            Student stu = new Student();
            stu.setName("小紅");
            stu.setTeacher(teacher);
            Student stu1 = new Student();
            stu1.setName("小明");
            stu1.setTeacher(teacher);
            sqlSession.insert(Teacher.class.getName()+".insert", teacher);
            sqlSession.insert(Student.class.getName()+".insert", stu);
            sqlSession.insert(Student.class.getName()+".insert", stu1);
        動(dòng)態(tài)插入配置
            <sql id="param">
                <trim suffixOverrides=",">
                    <if test="name!=null">
                        name,
                    </if>
                    <if test="age!=null">
                        age,
                    </if>
                    <if test="teacher!=null and teacher.id!=null">
                        t_id,
                    </if>
                </trim>
            </sql>
            <sql id="value">
                <trim suffixOverrides=",">
                    <if test="name!=null">
                        #{name},
                    </if>
                    <if test="age!=null">
                        #{age},
                    </if>
                    <if test="teacher!=null and teacher.id!=null">
                        #{teacher.id},
                    </if>
                </trim>
            </sql>
            <insert id="insert" parameterType="Student" useGeneratedKeys="true" keyProperty="id">
                insert into student (<include refid="param"/>) values(<include refid="value"/>)
            </insert>
        查詢(xún)多的一端
            Student.xml
                <resultMap type="Student" id="studentMap">
                    <id column="id" property="id"/>
                    <result column="name" property="name"/>
                    <result column="age" property="age"/>
                    <association property="teacher" column="t_id" select="com.shuai.mybatis.domain.Teacher.getById"/>
                </resultMap>
                <select id="getStudentfetchTeacher" parameterType="int" resultMap="studentMap">
                    select * from student where id=#{id};
                </select>
            Teacher.xml
                <select id="getById" parameterType="int" resultType="Teacher">
                    select * from teacher where id = #{id}
                </select>
            java代碼
                Student stu = sqlSession.selectOne(Student.class.getName()+".getStudentfetchTeacher", 1);
        查一的一端
            Student.xml
                <resultMap type="Student" id="studentBaseMap">
                    <id column="id" property="id"/>
                    <result column="name" property="name"/>
                    <result column="age" property="age"/>
                </resultMap>
            Teacher.xml
                <resultMap type="Teacher" id="teacherBaseMap">
                    <id column="id" property="id" />
                    <result column="name" property="name" />
                    <result column="age" property="age" />
                </resultMap>
                <resultMap type="Teacher" id="teacherMap">
                    <collection property="students" resultMap="com.shuai.mybatis.domain.Student.studentBaseMap"/>
                </resultMap>
                <select id="getAllById" parameterType="int" resultMap="teacherMap">
                    select * from teacher t inner join student s on t.id=s.t_id where t.id=#{id}
                </select>
            java代碼
                List<Teacher> selectList = sqlSession.selectList(Teacher.class.getName()+".getAllById", 1);
雙向關(guān)聯(lián)(一對(duì)一)
    sql:
        create table teacher(
            id int not null auto_increment comment '主鍵',
            name  varchar(20) not null default '' comment '姓名',
            age int not null default 0 comment '年齡',
            primary key(id)
        )engine=innoBD default charset=utf8;

        create table student(
            id int not null auto_increment comment '主鍵',
            name varchar(20) not null default '' comment '姓名',
            age int not null default 0 comment '年齡',
            t_id int not null,
            primary key(id),
            constraint fk_teacher_id foreign key (t_id) references teacher(id)
        )engine=innoDB default charset=utf8;
    映射文件
        Teacher.xml
            <resultMap type="Teacher" id="teacherBaseMap">
                <id column="id" property="id"/>
                <result column="name" property="name"/>
                <result column="age" property="age"/>
                <association property="student" column="t_id" select="com.shuai.mybatis.domain.Student.getOne"></association>
            </resultMap>
            <insert id="insert" parameterType="Teacher" useGeneratedKeys="true" keyProperty="id">
                insert into teacher (name,age) values (#{name},#{age})
            </insert>
            <select id="getOne" parameterType="int" resultMap="teacherBaseMap">
                select * from teacher t inner join student s on t.id = s.t_id and t.id=#{id}
            </select>
        Student.xml
            <resultMap type="Student" id="studentBaseMap">
                <id column="id" property="id"/>
                <result column="name" property="name"/>
                <result column="age" property="age"/>
            </resultMap>
            <insert id="insert" parameterType="Student">
                insert into student (name,age,t_id) values (#{name},#{age},#{teacher.id})
            </insert>   
            <select id="getOne" resultMap="studentBaseMap">
                select * from student where id = #{id}
            </select>
    測(cè)試
        增加
            Teacher teacher = new Teacher();
            teacher.setName("帥哥");
            teacher.setAge(30);
            Student student = new Student();
            student.setName("小明");
            student.setAge(20);
            student.setTeacher(teacher);
            sqlSession.insert(Teacher.class.getName()+".insert", teacher);
            sqlSession.insert(Student.class.getName()+".insert", student);
        查詢(xún)
            Teacher teacher = sqlSession.selectOne(Teacher.class.getName()+".getOne", 1);

返回Map類(lèi)型

ResultType="java.util.HashMap"
Map map = (Map)session.selectOne()

返回list集合/map集合


時(shí)間排序查詢(xún)


集合操作

List集合
    sql:
        create table users(
            id int primary key auto_increment comment '主鍵',
            name varchar(20) not null default '' comment '姓名'
        )engine=innoDB default charset=utf8;

        create table address(
            id int primary key auto_increment comment '主鍵',
            address varchar(20) not null default '' comment '地址',
            u_id int not null,
            constraint fk_user_address foreign key (u_id) references users(id)
        )engine=innoDB default charset=utf8;
    User.xml
        <mapper namespace="com.shuai.mybatis.domain.User">
            <resultMap type="User" id="userMap">
                <id column="id" property="id"/>
                <result column="name" property="name"/>
                <collection property="address" resultMap="com.shuai.mybatis.domain.Address.stringArray"></collection>
            </resultMap>
            <insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id">
                insert into users (name) values (#{name})
            </insert>
            <select id="getOne" parameterType="User" resultMap="userMap">
                select * from users u inner join address a on u.id=a.u_id where u.id=#{id}
            </select>
        </mapper>
    User.java
        public class User implements Serializable{
            private static final long serialVersionUID = 4980066222353642286L;
            private int id;
            private String name;
            private List<String> address = new ArrayList<String>();
        }
    Address.xml
        <mapper namespace="com.shuai.mybatis.domain.Address">
            <resultMap type="java.lang.String" id="stringArray">
                <result column="address" property="address"/>
            </resultMap>
            <insert id="insert" parameterType="Address">
                insert into address (address,u_id) values (#{address},#{user.id})
            </insert>
            <select id="getList" parameterType="int" resultType="java.util.List">
                select address from address where u_id=#{id}
            </select>
        </mapper>
    Address.java
        public class Address {
            private int id;
            private String addr;
            private User user;
        }
    插入
        User user = new User();
        user.setName("帥哥");
        user.getAddress().add("北京");
        user.getAddress().add("廣州");
        sqlSession.insert(User.class.getName()+".insert",user);
        for(String str : user.getAddress()){
            Address address = new Address();
            address.setAddress(str);
            address.setUser(user);
            sqlSession.insert(Address.class.getName()+".insert", address);
        }
    查詢(xún)
        User user = sqlSession.selectOne(User.class.getName()+".getOne", 1);
Set集合
    sql:
        create table user(
            id int primary key auto_increment comment '主鍵',
            name varchar(20) not null default '' comment '姓名'
        )engine=innoDB default charset=utf8;
        create table address(
            addr varchar(20) not null default '' comment '地址',
            u_id int not null comment '外鍵',
            constraint fk_u_a_id foreign key (u_id) references user(id)
        )engine=innoDB default charset=utf8;
    User.xml
        <mapper namespace="com.shuai.mybatis.domain.User">
            <resultMap type="User" id="baseMap">
                <id column="id" property="id"/>
                <result column="name" property="name"/>
                <collection property="address" resultMap="com.shuai.mybatis.domain.Address.addressMap"></collection>
            </resultMap>
            <insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id">
                insert into user (name) values (#{name})
            </insert>
            <select id="getOne" parameterType="int" resultMap="baseMap">
                select * from user u inner join address ad on u.id = ad.u_id where u.id=#{id}
            </select>
        </mapper>
    User.java
        public class User implements Serializable{
            private static final long serialVersionUID = 4980066222353642286L;
            private int id;
            private String name;
            private Set<String> address = new HashSet<String>();
        }
    Address.xml
        <mapper namespace="com.shuai.mybatis.domain.Address">
            <resultMap type="java.lang.String" id="addressMap">
                <result column="addr" property="addr"/>
            </resultMap>
            <insert id="insert" parameterType="Address">
                insert into address(addr,u_id) values (#{addr},#{user.id})
            </insert>
        </mapper>
    Address.java
        public class Address {
            private String addr;
            private User user;
        }
    測(cè)試
        插入
            User user = new User();
            user.setName("帥哥");
            user.getAddress().add("北京");
            user.getAddress().add("廣州");
            sqlSession.insert(User.class.getName()+".insert",user);
            for(String str : user.getAddress()){
                Address address = new Address();
                address.setAddr(str);
                address.setUser(user);
                sqlSession.insert(Address.class.getName()+".insert", address);
            }
        查詢(xún)
            User user = sqlSession.selectOne(User.class.getName()+".getOne", 1);
Map集合
    

繼承操作


延遲加載


mybatis與java數(shù)據(jù)類(lèi)型映射


緩存

一級(jí)緩存
    session
二級(jí)緩存
    開(kāi)啟二級(jí)緩存mybatis-config.xml
        <configuration>
            <settings>
                <setting name="cacheEnabled" value="true"/>
            </settings>
        </configuration>
    Teacher.java
        注意:此類(lèi)一定要實(shí)現(xiàn)Serializable接口
    映射文件Teacher.xml
        <mapper namespace="com.shuai.mybatis.domain.Teacher">
            <cache size="2" eviction="LRU" flushInterval="10000" />
        </mapper>
        注意:
            默認(rèn)所有的查詢(xún)都支持(建議僅僅用單條記錄查詢(xún))
            size: 內(nèi)存中支持的最大對(duì)象數(shù)量
            eviction: 替換策略: FIFO  LRU
            flushInterval: 設(shè)置刷新的時(shí)間間隔, 如果沒(méi)有配置則 發(fā)送SQL語(yǔ)句的時(shí)候及時(shí)更新

定義數(shù)據(jù)處理器巷燥?赡盘??g志尽陨享!(需要再處理)

創(chuàng)建日期處理器
    public class DateTypeHandler implements TypeHandler<String> {
        public String getResult(ResultSet rs, String columnName) throws SQLException {
            Date value = rs.getTimestamp(columnName);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return format.format(value);
        }
    }
在全局映射文件mybatis-config.xml配置處理器
    <typeHandlers>
        <typeHandler handler="com.shuai.mybatis.typehandler.DateTypeHandler" javaType="string" jdbcType="TIMESTAMP"/>
    </typeHandlers>
    <typeAliases>
        <typeAlias type="com.shuai.mybatis.typehandler.DateTypeHandler" alias="dateTypeHandler"/>
    </typeAliases>
在映射文件中使用
    <resultMap type="User" id="userMap">
        <result column="birth" property="birth" typeHandler="dateTypeHandler"/>
    </resultMap>
注意:做專(zhuān)門(mén)的數(shù)據(jù)顯示處理
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市钝腺,隨后出現(xiàn)的幾起案子霉咨,更是在濱河造成了極大的恐慌,老刑警劉巖拍屑,帶你破解...
    沈念sama閱讀 212,080評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件途戒,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡僵驰,警方通過(guò)查閱死者的電腦和手機(jī)喷斋,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,422評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)蒜茴,“玉大人星爪,你說(shuō)我怎么就攤上這事》鬯剑” “怎么了顽腾?”我有些...
    開(kāi)封第一講書(shū)人閱讀 157,630評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)诺核。 經(jīng)常有香客問(wèn)我抄肖,道長(zhǎng),這世上最難降的妖魔是什么窖杀? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,554評(píng)論 1 284
  • 正文 為了忘掉前任漓摩,我火速辦了婚禮,結(jié)果婚禮上入客,老公的妹妹穿的比我還像新娘管毙。我一直安慰自己腿椎,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,662評(píng)論 6 386
  • 文/花漫 我一把揭開(kāi)白布夭咬。 她就那樣靜靜地躺著啃炸,像睡著了一般。 火紅的嫁衣襯著肌膚如雪卓舵。 梳的紋絲不亂的頭發(fā)上南用,一...
    開(kāi)封第一講書(shū)人閱讀 49,856評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音边器,去河邊找鬼。 笑死托修,一個(gè)胖子當(dāng)著我的面吹牛忘巧,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播睦刃,決...
    沈念sama閱讀 39,014評(píng)論 3 408
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼砚嘴,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了涩拙?” 一聲冷哼從身側(cè)響起际长,我...
    開(kāi)封第一講書(shū)人閱讀 37,752評(píng)論 0 268
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎兴泥,沒(méi)想到半個(gè)月后工育,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,212評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡搓彻,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,541評(píng)論 2 327
  • 正文 我和宋清朗相戀三年如绸,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片旭贬。...
    茶點(diǎn)故事閱讀 38,687評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡怔接,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出稀轨,到底是詐尸還是另有隱情扼脐,我是刑警寧澤,帶...
    沈念sama閱讀 34,347評(píng)論 4 331
  • 正文 年R本政府宣布奋刽,位于F島的核電站瓦侮,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏佣谐。R本人自食惡果不足惜脏榆,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,973評(píng)論 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望台谍。 院中可真熱鬧须喂,春花似錦吁断、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,777評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至是己,卻和暖如春又兵,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背卒废。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,006評(píng)論 1 266
  • 我被黑心中介騙來(lái)泰國(guó)打工沛厨, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人摔认。 一個(gè)月前我還...
    沈念sama閱讀 46,406評(píng)論 2 360
  • 正文 我出身青樓逆皮,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親参袱。 傳聞我的和親對(duì)象是個(gè)殘疾皇子电谣,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,576評(píng)論 2 349

推薦閱讀更多精彩內(nèi)容