介绍
概述
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
注意:
> 换为 >
< 换为 <
增加
<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 > #{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>
注意:做专门的数据显示处理