简述
MyBatis是一种ORM框架,即:对象关系映射。是指数据库和Java对象可相互转化,这是基于JDBC的二次开发。与JDBC不同的是,MyBatis在完成一些配置之后,需要做得仅仅是在一个文件中写sql语句。通过反向代理可大大减轻开发过程中代码冗余的编写。MyBatis的主要内容包括输入映射、输出映射、动态标签库、多表操作语句、MyBatis缓存。
前提
导包
导入需要用到的依赖。pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.simon</groupId>
<artifactId>my-batis-qucik-start</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<!--Maven增强,是为了让Mapper.xml和Mapper接口位于src的同一目录下,当然编译之后还是在同一目录下-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>
**/*.xml
</include>
</includes>
</resource>
</resources>
</build>
</project>
配置
MyBatis.xml,MyBatis接口
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="jdbc.properties"/>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<!--<package name="com.simon.bean"/>-->
<typeAlias type="com.simon.bean.User" alias="user"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/simon/Mapper.xml"/>
</mappers>
</configuration>
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/29_db1?useSSL=false&characterEncoding=utf8
username=root
password=123456
package com.simon.bean;
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
简单的增删改查
package com.simon;
import com.simon.bean.User;
import java.util.List;
public interface Mapper {
User selectUser();
void insertUser(User user);
void deleteUserById(Integer id1,Integer id2,Integer id3);
void updateUserById(Integer id);
List<User> selectUserList();
}
<?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.simon.Mapper">
<select id="selectUser" resultType="user">
select * from user where id = 1
</select>
<insert id="insertUser" parameterType="user">
insert into user values(#{id},#{username},#{password},#{age})
</insert>
<delete id="deleteUserById">
delete from user where id = #{param1} or id = #{param2} or id = #{param3}
</delete>
<update id="updateUserById">
update user set age = 99 where id = #{id}
</update>
<select id="selectUserList" resultType="user">
select * from user
</select>
</mapper>
主要内容
输入映射
- pom.xml
- mybatis-config.xml
- jdbc.properties
- User类添加注解别名:”user” ```java package com.simon;
import com.simon.bean.User; import org.apache.ibatis.annotations.Param;
import java.util.List; import java.util.Map;
public interface Mapper { User selectUserById(Integer id); User selectUserById2(@Param(“uid”) Integer id);
User selectUserByIdAndUsername(@Param("id") Integer id,
@Param("name") String username);
Integer insertUserByObject(@Param("user") User user);
List<User> selectUserByIdOrUsername(@Param("map") Map map);
List<User> selectUserByIndex(Integer id,String username);
List<User> selectUserByTableName(@Param("tableName") String tableName);
List<User> selectUserByColumnName(@Param("columnName") String columnName);
}
```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.simon.Mapper">
<select id="selectUserById" resultType="user">
select * from user where id = #{id}
</select>
<select id="selectUserById2" resultType="user">
select * from user where id = #{uid}
</select>
<select id="selectUserByIdAndUsername" resultType="user">
select * from user where id = #{id} and username = #{name}
</select>
<insert id="insertUserByObject" parameterType="user">
insert into user values(#{user.id},#{user.username},#{user.password},#{user.age})
</insert>
<select id="selectUserByIdOrUsername" resultType="user">
select * from user where id = #{map.id} or username = #{map.username}
</select>
<select id="selectUserByIndex" resultType="user">
select * from user where id = #{param1} or username = #{param2}
</select>
<select id="selectUserByTableName" resultType="user">
select * from ${tableName} limit 10
</select>
<select id="selectUserByColumnName" resultType="user">
select * from user group by ${columnName}
</select>
</mapper>
package com.simon;
import com.simon.bean.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
public class ParamTest {
public static SqlSession sqlSession = null;
static Mapper mapper;
@BeforeClass
public static void init() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
sqlSession = sqlSessionFactory.openSession();
mapper = sqlSession.getMapper(Mapper.class);
}
@AfterClass
public static void destory(){
sqlSession.commit();
sqlSession.close();
}
//一个不带别名简单类型的入参
@Test
public void testSelectUserById(){
User user = mapper.selectUserById(1);
System.out.println(user);
}
//一个带别名的简单类型的入参
@Test
public void testSelectUserById2(){
User user = mapper.selectUserById2(2);
System.out.println(user);
}
//多个带别名的简单类型的入参
@Test
public void testSelectUserByIdAndUsername(){
User user = mapper.selectUserByIdAndUsername(2,"兰钊");
System.out.println(user);
}
//带别名的Object类型的入参
@Test
public void testinsertUserByObject(){
User user = new User();
user.setId(7);
user.setUsername("张三");
user.setPassword("废话转");
user.setAge(78);
Integer affectedRows = mapper.insertUserByObject(user);
System.out.println("affectedRows:" + affectedRows);
}
//通过Map作为入参(不推荐)
@Test
public void testselectUserByIdOrUsername(){
HashMap<String, Object> map = new HashMap<>();
map.put("id",1);
map.put("username","张三");
List<User> userList = mapper.selectUserByIdOrUsername(map);
}
//通过位置作为入参(不推荐)
@Test
public void testselectUserByIndex(){
List<User> userList = mapper.selectUserByIndex(1, "天明");
System.out.println(userList);
}
//$和#:关于$的优势:传递表名或者列名的时候必须使用$,分库分表的时候用得多
@Test
public void testselectUserByTableName(){
List<User> userList = mapper.selectUserByTableName("user");
System.out.println(userList);
}
@Test
public void testselectUserByColumnName(){
List<User> userList = mapper.selectUserByColumnName("age");
System.out.println(userList);
}
}
输出映射
输出映射,包含单个字段、单个字段列表的输出映射,对象、对象列表的输出映射、ResuletMap输出映射。
单个字段
字段列表,by list
字段列表,by array
单个对象
单个对象列表
单个对象,解决对应不上的问题:Result
对象列表,解决对应不上的问题:Result
package com.simon;
import com.simon.bean.User;
import com.simon.bean.UserVO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface Mapper {
Integer selectUserAgeById(Integer id);
List<Integer> selectUserAges();
Integer[] selectUserAges2();
User selectUserById(Integer id);
UserVO selectUserById2(Integer id);
List<User> selectUserList();
UserVO selectUserVOById3(Integer id);
List<UserVO> selectUserVOList();
}
<?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.simon.Mapper">
<select id="selectUserAgeById" resultType="int">
select age from user where id = #{id}
</select>
<select id="selectUserAges" resultType="int">
select age from user
</select>
<select id="selectUserAges2" resultType="int">
select age from user
</select>
<select id="selectUserById" resultType="com.simon.bean.User">
select * from user where id = #{id}
</select>
<select id="selectUserById2" resultType="com.simon.bean.UserVO">
SELECT
id AS id,
username AS name,
PASSWORD AS passwd,
age AS age
FROM
USER
WHERE
id = #{id}
</select>
<select id="selectUserList" resultType="user">
select * from user
</select>
<!--ResultMap-->
<resultMap id="selectUserVO" type="com.simon.bean.UserVO">
<id column="id" property="id"/>
<result column="username" property="name"/>
<result column="password" property="passwd"/>
<result column="age" property="age"/>
</resultMap>
<select id="selectUserVOById3" resultMap="selectUserVO">
select * from user where id = #{id}
</select>
<select id="selectUserVOList" resultMap="selectUserVO">
select * from user
</select>
</mapper>
package com.simon;
import com.simon.bean.User;
import com.simon.bean.UserVO;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
public class OutPutMappingTest {
public static SqlSession sqlSession = null;
static Mapper mapper;
@BeforeClass
public static void init() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
sqlSession = sqlSessionFactory.openSession();
mapper = sqlSession.getMapper(Mapper.class);
}
@AfterClass
public static void destory(){
sqlSession.commit();
sqlSession.close();
}
//输出映射,包含单个字段、单个字段列表的输出映射,
//对象、对象列表的输出映射
//ResuletMap输出映射
//单个字段
@Test
public void testSelectUserAgeById(){
Integer age = mapper.selectUserAgeById(2);
System.out.println("age:" + age);
}
//字段列表,by list
@Test
public void testSelectUserAges(){
List<Integer> ages = mapper.selectUserAges();
System.out.println(ages);
}
//字段列表,by array
@Test
public void testSelectUserAges2(){
Integer[] ages = mapper.selectUserAges2();
for (Integer age : ages) {
System.out.println("age:" + age);
}
}
//单个对象
@Test
public void testSelectUserById(){
User user = mapper.selectUserById(2);
System.out.println(user);
}
//单个对象,解决对应不上的问题:起别名
@Test
public void testSelectUserById2(){
UserVO user = mapper.selectUserById2(3);
System.out.println(user);
}
//单个对象列表
@Test
public void testSelectUserList(){
List<User> userList = mapper.selectUserList();
System.out.println(userList);
}
//单个对象,解决对应不上的问题:Result
@Test
public void testSelectUserById3(){
UserVO userVO = mapper.selectUserVOById3(5);
System.out.println(userVO);
}
//对象列表,解决对应不上的问题:Result
@Test
public void testSelectUserVO(){
List<UserVO> userVOList = mapper.selectUserVOList();
for (UserVO userVO : userVOList) {
System.out.println(userVO);
}
}
}
动态标签库
User类、Mapper接口、Mapper.xml实际在用。
package com.simon;
import com.simon.bean.User;
import com.simon.bean.UserVO;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class OutPutMappingTest {
public static SqlSession sqlSession = null;
static Mapper mapper;
@BeforeClass
public static void init() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
sqlSession = sqlSessionFactory.openSession();
mapper = sqlSession.getMapper(Mapper.class);
}
@AfterClass
public static void destory(){
sqlSession.commit();
sqlSession.close();
}
//输出映射,包含单个字段、单个字段列表的输出映射,
//对象、对象列表的输出映射
//ResuletMap输出映射
//where...if
@Test
public void testSelectUserBySelf(){
User user = new User();
user.setId(2);
user = mapper.selectUserBySelf(user);
System.out.println(user);
}
//if...else...---->choose..when..otherwise..
@Test
public void testSelectUserListByAge(){
List<User> users = mapper.selectUserListByAge(28);
System.out.println(users);
}
//传什么条件,改什么条件。trim set,set更简洁
@Test
public void testUpdateUserWithTrim(){
User user = new User();
user.setPassword("我的快餐名!");
user.setId(7);
Integer affectedRows = mapper.updateUserWithTrim(user);
System.out.println("affectedRows:" + affectedRows);
}
@Test
public void testUpdateUserWithSet(){
User user = new User();
user.setPassword("我的第二个快餐名!");
user.setId(7);
Integer affectedRows = mapper.updateUserWithSet(user);
System.out.println("affectedRows:" + affectedRows);
}
//sql...include 抽取公共sql片段,注意怎样抽取
@Test
public void testSelectUserWithSqlIncludes(){
List<User> userList = mapper.selectUserWithSqlIncludes();
System.out.println(userList);
}
//foreach....循环 :批量插入、通过in查找
//注意属性collection,若未指定注解,则以list或array为默认
@Test
public void testInsertUserForeach(){
User user1 = new User();
user1.setId(8);
user1.setUsername("张阿发");
user1.setPassword("恭喜发财");
user1.setAge(37);
User user2 = new User();
user2.setId(9);
user2.setUsername("李孝九");
user2.setPassword("999,感冒灵");
user2.setAge(89);
ArrayList<User> users = new ArrayList<>();
users.add(user1);
users.add(user2);
Integer affectedRows = mapper.insertUserWithForeach(users);
System.out.println("affectedRows:" + affectedRows);
}
@Test
public void testSelectUserWithForeach(){
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < 6; i++) {
list.add(1+i);
}
List<User> userList = mapper.selectUserByIdListWithForeach(list);
System.out.println(userList);
}
//主键自增,一般要先插入后查询。其优化之道是selectKey
@Test
public void testInsertUserThenSelectIdWithSelectKey(){
User user = new User();
user.setId(null);
user.setUsername("金十顺");
user.setPassword("十全十美");
user.setAge(47);
Integer affectedRows = mapper.insertUserThenSelectIdWithSelectKey(user);
System.out.println("affectedRows:" + affectedRows);
System.out.println("获取到的用户id:" + user.getId());
}
//使用useGeneratedKeys比SelectKey更简单
@Test
public void testInsertUserThenSelectIdWithGeneratedKeys(){
User user = new User();
user.setId(null);
user.setUsername("张良");
user.setPassword("足智多谋");
user.setAge(43);
Integer affectedRows = mapper.insertUserThenSelectIdWithGeneratedKeys(user);
System.out.println("affectedRows:" + affectedRows);
System.out.println("获取到的用户id:" + user.getId());
}
}
package com.simon;
import com.simon.bean.User;
import com.simon.bean.UserVO;
import org.apache.ibatis.annotations.Param;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public interface Mapper {
//动态sql标签库,where--if--choose...when...otherwise
//where,if,20
//where的作用:动态拼接,首个自动取出and/or,不满足则去除where,直接select * from user
User selectUserBySelf(@Param("user") User user);
//if...else...---->choose..when..otherwise..
List<User> selectUserListByAge(@Param("age") Integer age);
//传什么条件,改什么条件。trim set,set更简洁
Integer updateUserWithTrim(@Param("user") User user);
Integer updateUserWithSet(@Param("user") User user);
List<User> selectUserWithSqlIncludes();
Integer insertUserWithForeach(@Param("users") ArrayList<User> users);
List<User> selectUserByIdListWithForeach(@Param("idList") List<Integer> idList);
Integer insertUserThenSelectIdWithSelectKey(@Param("user") User user);
Integer insertUserThenSelectIdWithGeneratedKeys(@Param("user") User user);
}
<?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.simon.Mapper">
<select id="selectUserBySelf" resultType="com.simon.bean.User">
select * from user
<where>
<if test="user.id != null">
and id = #{user.id}
</if>
<if test="user.username != null">
and username = #{user.username}
</if>
<if test="user.password != null">
and password = #{user.password}
</if>
<if test="user.age != null">
and age = #{user.age}
</if>
</where>
</select>
<select id="selectUserListByAge" resultType="com.simon.bean.User">
select * from user
<where>
<choose >
<when test="age gt 30">
age >= 30
</when>
<otherwise>
age < 30
</otherwise>
</choose>
</where>
</select>
<update id="updateUserWithTrim" parameterType="com.simon.bean.User">
update user
<trim prefix="set" suffixOverrides=",">
<if test="user.username != null">
username = #{user.username},
</if>
<if test="user.password != null">
password = #{user.password},
</if>
<if test="user.age != null">
age = #{user.age},
</if>
</trim>
<where>
id = #{user.id}
</where>
</update>
<update id="updateUserWithSet" parameterType="com.simon.bean.User">
update user
<set>
<if test="user.username != null">
username = #{user.username},
</if>
<if test="user.password != null">
password = #{user.password},
</if>
<if test="user.age != null">
age = #{user.age},
</if>
</set>
<where>
id = #{user.id}
</where>
</update>
<sql id="column_lists">
id,username,password,age
</sql>
<select id="selectUserWithSqlIncludes" resultType="com.simon.bean.User">
select <include refid="column_lists"/> from user
</select>
<insert id="insertUserWithForeach" parameterType="com.simon.bean.User">
insert into user
values <foreach collection="users" item="user" separator=",">
(#{user.id},#{user.username},#{user.password},#{user.age},now)
</foreach>
</insert>
<!--注意此处,是#{id}而不是#{id.id},separator也要写-->
<!--foreach是检验动态sql学得好不好的一个重要方面-->
<select id="selectUserByIdListWithForeach" resultType="com.simon.bean.User">
select <include refid="column_lists"/>
from user
<where>
id in
<foreach collection="idList" separator="," item="id" open="(" close=")">
#{id}
</foreach>
</where>
</select>
<insert id="insertUserThenSelectIdWithSelectKey" parameterType="com.simon.bean.User">
<selectKey order="AFTER" keyColumn="id" keyProperty="user.id" resultType="integer">
select LAST_INSERT_ID()
</selectKey>
insert into user values (#{user.id},#{user.username},#{user.password},#{user.age})
</insert>
<insert id="insertUserThenSelectIdWithGeneratedKeys" parameterType="com.simon.bean.User"
useGeneratedKeys="true" keyProperty="user.id" keyColumn="id">
insert into user values (#{user.id},#{user.username},#{user.password},#{user.age})
</insert>
</mapper>