mybatis

介绍

概述
    MyBatis最早源自Apache基金会的一个开源项目iBatis.
    2010年这个项目由Apache software foundation迁移到google code,并且改名为MyBatis;
    MyBatis是支持普通SQL查询,存储程和高级映射的优秀持久层框架。
    MyBati封装了几乎所有的JDBC代码和参数的手工设置以及结果集的检索;
    MyBatist使用简单的XML或注解做配置和定义映射关系将Java的POJOs(Plain Old Java Objects)映射成数据库中的记录.
下载
    http://www.mybatis.org/mybatis-3/
Mybatis体系结构
    1.加载配置:配置来源于两个地方,一处是配置文件,一处是Java代码的注解,将SQL的配置信息加载成为一个个MappedStatement对象(包括了传入参数映射配置、执行的SQL语句、结果映射配置),存储在内存中。
    2.SQL解析:当API接口层接收到调用请求时,会接收到传入SQL的ID和传入对象(可以是Map、JavaBean或者基本数据类型),Mybatis会根据SQL的ID找到对应的MappedStatement,然后根据传入参数对象对MappedStatement进行解析,解析后可以得到最终要执行的SQL语句和参数。
    3.SQL执行:将最终得到的SQL和参数拿到数据库进行执行,得到操作数据库的结果。
    4.结果映射:将操作数据库的结果按照映射的配置进行转换,可以转换成HashMap、JavaBean或者基本数据类型,并将最终结果返回。
MyBatis配置文件
    MyBatis框架的XML配置文件包含下面两种类型
        1.mybatis-config.xml (1个)
            主配置文件,用于指定数据库连接参数和框架参数
            在mybatis官网查看http://www.mybatis.org/mybatis-3/getting-started.html
        2.DepartmentMapper.xml (n个)
            映射定义文件,用于定义SQL语句和映射信息
            在mybatis官网查看http://www.mybatis.org/mybatis-3/sqlmap-xml.html
框架API简介 
    SqlSessionFactoryBuilder
        该对象负责根据MyBatis配置文件mybatis-config.xml构建SqISessionFaciory实例
    SqlSessionFactory
        每一个MyBatis的应用程序都以一个SqISessionFactory对象为核心。该对象负责创建SqlSession对象实例
    SqlSession
        该对像包含了所有执行SQL操作的方法,用于执行己映射的SQL语句
使用步骤
    1.为工程添加MyBatis开发包( mybatis-x.x.x.jar )和数据库驱动包
    2.在src下添加MyBatis配置文件SqIMapConfig.xml
    3.修改SqIMapConfig.xml指定数据库连接参数
    4.利用MyBatis API编程,获取SqISession实例

mybatis

第一种方式步骤
    1.maven引入依赖包
        <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.创建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.创建数据库表/创建实体类
        public class User {
            private int id;
            private String name;
            private int age;
        }
    4.创建实体类配置文件(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.测试
        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引入依赖包
    2.创建mybatis-config.xml
    3.创建数据库表/创建实体类
    4.创建实体类Mapper接口
        public interface UserDao {
            public void insert(User user);
        }
    5.创建实体类配置文件(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.测试
        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>

增删改查/分页查询

注意:增加/删除/修改 都可以使用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);
    增加时返回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" 设置是否使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的主键字段中
        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);
查询
    根据id查询
        <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);
    根据名字模糊查询
        <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%");
    分页查询
        <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} //注意:这里必须要这样写
            </select>
            RowBounds bounds = new RowBounds(0,5);
            List<User> list = sqlSession.selectList(User.class.getName()+".getLimit", bounds);

别名配置

在主配置文件中定义类的别名
    <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>
注意:不区分大小写

定义结果集

在映射文件中定义结果集
    <resultMap type="User" id="userMap">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="age" property="age"/>
    </resultMap>
在映射文件中使用结果集
    <select id="getByPage" parameterType="java.util.Map" resultMap="userMap">
        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", 3);
    dataMap.put("size", 3);
    List<User> list = sqlSession.selectList(User.class.getName()+".getByPage", dataMap);
注意:
    重点在配置关联映射的时候使用

动态SQL(增删改查/分页查询)

总结
    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();
    }
查询
    <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();
    }

关联操作

双向关联(多对多)
    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);
            }
        查询
            List<Student> selectList = sqlSession.selectList(Student.class.getName()+".getAll", 1);
            List<Teacher> selectList1 = sqlSession.selectList(Teacher.class.getName()+".getAll", 1);
双向关联(一对多)
    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);
        动态插入配置
            <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>
        查询多的一端
            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);
双向关联(一对一)
    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>
    测试
        增加
            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);
        查询
            Teacher teacher = sqlSession.selectOne(Teacher.class.getName()+".getOne", 1);

返回Map类型

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

返回list集合/map集合


时间排序查询


集合操作

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);
        }
    查询
        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;
        }
    测试
        插入
            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);
            }
        查询
            User user = sqlSession.selectOne(User.class.getName()+".getOne", 1);
Map集合
    

继承操作


延迟加载


mybatis与java数据类型映射


缓存

一级缓存
    session
二级缓存
    开启二级缓存mybatis-config.xml
        <configuration>
            <settings>
                <setting name="cacheEnabled" value="true"/>
            </settings>
        </configuration>
    Teacher.java
        注意:此类一定要实现Serializable接口
    映射文件Teacher.xml
        <mapper namespace="com.shuai.mybatis.domain.Teacher">
            <cache size="2" eviction="LRU" flushInterval="10000" />
        </mapper>
        注意:
            默认所有的查询都支持(建议仅仅用单条记录查询)
            size: 内存中支持的最大对象数量
            eviction: 替换策略: FIFO  LRU
            flushInterval: 设置刷新的时间间隔, 如果没有配置则 发送SQL语句的时候及时更新

定义数据处理器???!!(需要再处理)

创建日期处理器
    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>
注意:做专门的数据显示处理
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,194评论 6 490
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,058评论 2 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 156,780评论 0 346
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,388评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,430评论 5 384
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,764评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,907评论 3 406
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,679评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,122评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,459评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,605评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,270评论 4 329
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,867评论 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,734评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,961评论 1 265
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,297评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,472评论 2 348

推荐阅读更多精彩内容