介紹
概述
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
注意:
> 換為 >
< 換為 <
增加
<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 > #{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ù)顯示處理