准备
# jdbc.properties
jdbc.url=jdbc:mysql://192.168.208.192:3306/test?characterEncoding=utf-8
jdbc.driver=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=root
# log4j.properties
log4j.rootLogger = debug,stdout,E
### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
### 输出DEBUG 级别以上的日志到=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### 输出ERROR 级别以上的日志到=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
<!-- mybatis/SqlMapConfig.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>
<!--
加载属性文件
先加载内部标签,再加载外部文件,名称一致时,会覆盖内部标签内容
-->
<properties resource="jdbc.properties"/>
<!--别名扫描-->
<typeAliases>
<package name="com.zze.mybatis.pojo" />
</typeAliases>
<!-- 和 spring 整合后 environments配置将废除-->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理-->
<transactionManager type="JDBC"/>
<!-- 数据库连接池-->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 加载映射文件 -->
<mappers>
<package name="com.zze.mybatis.mapper"/>
</mappers>
</configuration>
// com.zze.mybatis.pojo.User
import java.util.Date;
public class User {
private Integer id;
private String name;
private Date birthday;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", birthday=" + birthday +
'}';
}
}
// com.zze.mybatis.util.SqlSessionFactoryUtil
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 java.io.IOException;
import java.io.InputStream;
public class SqlSessionFactoryUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
// 创建 SqlSessionFactoryBuilder 对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
// 创建核心配置文件的输入流
InputStream resourceAsStream = null;
try {
resourceAsStream = Resources.getResourceAsStream("mybatis/SqlMapConfig.xml");
} catch (IOException e) {
e.printStackTrace();
}
// 创建 Session 工厂
sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);
}
/**
* 打开一个 Session
*
* @return SqlSession 实例
*/
public static SqlSession openSession() {
return sqlSessionFactory.openSession();
}
/**
* 打开一个 Session
*
* @param autoCommit 是否自动提交事务
* @return SqlSession 实例
*/
public static SqlSession openSession(Boolean autoCommit) {
return sqlSessionFactory.openSession(autoCommit);
}
}
<!-- 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.zze.mybatis</groupId>
<artifactId>mybatis_test2</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.0-rc1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0-rc1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.11.0.GA</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
示例
字段映射-resultMap
如果表字段名与 POJO 属性名不一致,则可通过 resultMap
标签配置表字段与 POJO 属性的映射关系:
<!-- com/zze/mybatis/mapper/UserMapper.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.zze.mybatis.mapper.UserMapper">
<resultMap id="userMap" type="user">
<!--
id 配置对应主键字段
property:属性名
column:字段名
-->
<id property="id" column="uid"/>
<!--
result 配置普通属性字段
property:属性名
column:字段名
-->
<result property="name" column="username"/>
<!--
非关联查询时
属性名与字段名相同的 result 映射可以省略不写
-->
<!--<result property="birthday" column="birthday"/>-->
</resultMap>
<select id="getAll" resultMap="userMap">
select id uid,name username,birthday from user;
</select>
</mapper>
// com.zze.mybatis.mapper.UserMapper
import com.zze.mybatis.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> getAll();
}
import com.zze.mybatis.mapper.UserMapper;
import com.zze.mybatis.pojo.User;
import com.zze.mybatis.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
public class MyBatisTest {
private UserMapper userMapper;
@Before
public void init() {
SqlSession sqlSession = SqlSessionFactoryUtil.openSession();
userMapper = sqlSession.getMapper(UserMapper.class);
}
@Test
public void test() {
List<User> all = userMapper.getAll();
for (User user : all) {
System.out.println(user);
}
/*
==> Preparing: select id uid,name username,birthday from user;
*/
}
}
动态sql-where&if
当 sql 条件需要动态拼接时,可以使用 where
和 if
标签:
<!-- com/zze/mybatis/mapper/UserMapper.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.zze.mybatis.mapper.UserMapper">
<select id="getByUser" resultType="user" parameterType="user">
select id,name,birthday from user
<where>
<if test="name!=null and name!=''">
name like '%${name}%'
</if>
</where>
</select>
</mapper>
// com.zze.mybatis.mapper.UserMapper
import com.zze.mybatis.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> getByUser(User user);
}
package com.zze.mybatis.test;
import com.zze.mybatis.mapper.UserMapper;
import com.zze.mybatis.pojo.User;
import com.zze.mybatis.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
public class MyBatisTest {
private UserMapper userMapper;
@Before
public void init() {
SqlSession sqlSession = SqlSessionFactoryUtil.openSession();
userMapper = sqlSession.getMapper(UserMapper.class);
}
@Test
public void test() {
User user = new User();
user.setName("张");
List<User> userList1 = userMapper.getByUser(user);
userList1.forEach(u-> System.out.println(u));
/*
==> Preparing: select id,name,birthday from user WHERE name like '%张%'
*/
user.setName(null);
List<User> userList2 = userMapper.getByUser(user);
userList2.forEach(u-> System.out.println(u));
/*
==> Preparing: select id,name,birthday from user
*/
}
}
sql片段-sql&include
当一段 sql 要被频繁在多处使用时,可以将这段 sql 单独抽取出来:
<!-- com/zze/mybatis/mapper/UserMapper.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.zze.mybatis.mapper.UserMapper">
<sql id="userAllField">
id,name,birthday
</sql>
<select id="getAll" resultType="user">
select
<include refid="userAllField"/>
from user
</select>
</mapper>
// com.zze.mybatis.mapper.UserMapper
import com.zze.mybatis.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> getAll();
}
package com.zze.mybatis.test;
import com.zze.mybatis.mapper.UserMapper;
import com.zze.mybatis.pojo.User;
import com.zze.mybatis.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
public class MyBatisTest {
private UserMapper userMapper;
@Before
public void init() {
SqlSession sqlSession = SqlSessionFactoryUtil.openSession();
userMapper = sqlSession.getMapper(UserMapper.class);
}
@Test
public void test() {
List<User> userList = userMapper.getAll();
userList.forEach(u-> System.out.println(u));
/*
==> Preparing: select id,name,birthday from user
*/
}
}
循环-foreach
编写 sql 时也可以通过传入集合来动态拼装条件:
// com.zze.mybatis.pojo.QueryVO
package com.zze.mybatis.pojo;
import java.util.List;
public class QueryVO {
private List<Integer> idList;
public List<Integer> getIdList() {
return idList;
}
public void setIdList(List<Integer> idList) {
this.idList = idList;
}
}
<!-- com/zze/mybatis/mapper/UserMapper.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.zze.mybatis.mapper.UserMapper">
<select id="getByIdList" resultType="user" parameterType="queryvo">
select * from user
<where>
<foreach collection="idList" open="id in (" close=")" separator="," item="id">
#{id}
</foreach>
</where>
</select>
</mapper>
// com.zze.mybatis.mapper.UserMapper
import com.zze.mybatis.pojo.QueryVO;
import com.zze.mybatis.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> getByIdList(QueryVO queryVO);
}
package com.zze.mybatis.test;
import com.zze.mybatis.mapper.UserMapper;
import com.zze.mybatis.pojo.QueryVO;
import com.zze.mybatis.pojo.User;
import com.zze.mybatis.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
public class MyBatisTest {
private UserMapper userMapper;
@Before
public void init() {
SqlSession sqlSession = SqlSessionFactoryUtil.openSession();
userMapper = sqlSession.getMapper(UserMapper.class);
}
@Test
public void test() {
QueryVO queryVO = new QueryVO();
queryVO.setIdList(Arrays.asList(1, 2, 3));
List<User> userList = userMapper.getByIdList(queryVO);
userList.forEach(u-> System.out.println(u));
/*
==> Preparing: select * from user WHERE id in ( ? , ? , ? )
==> Parameters: 1(Integer), 2(Integer), 3(Integer)
*/
}
}
要注意的是 mybatis 的 Mapper 参数不支持直接传入集合,但我们可以如上示例将它放在包装类中传入。
评论区