标签: Java与存储
MyBatis前身是iBatis,是一个基于Java的数据持久层/对象关系映射(ORM)框架.
MyBatis是对JDBC的封装,使开发人员只需关注SQL本身,而不需花费过多的精力去处理如注册驱动、设置参数、创建Connection
/Statement
、解析结果集等JDBC过程性代码.MyBatis基于XML/注解的方式配置Statement
,执行SQL,并将执行结果映射成Java对象, 大大降低了数据库开发的难度.
MyBatis is a first class persistence framework with support for custom SQL, stored procedures and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records.
– MyBatis项目地址/在线文档.
使用MyBatis需要在pom.xml中添加如下依赖:
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.3.0version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.36version>
dependency>
<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://host:port/db?characterEncoding=utf-8"/>
<property name="username" value="username"/>
<property name="password" value="password"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="mybatis/mapper/UserDAO.xml"/>
mappers>
configuration>
<mapper namespace="namespace">
<select id="selectUserById" parameterType="java.lang.Integer" resultType="com.fq.domain.User">
SELECT * FROM user WHERE id = #{id};
select>
<select id="selectUserByName" parameterType="java.lang.String" resultType="com.fq.domain.User">
SELECT * FROM user WHERE name LIKE '%${value}%';
select>
mapper>
属性 | 描述 |
---|---|
namespace |
命名空间,用于隔离SQL语句 |
parameterType |
定义SQL输入映射类型,MyBatis通过OGNL从输入对象中获取参数传入SQL语句. |
resultType |
定义SQL输出映射类型,MyBatis将SQL查询结果的一行记录映射为resultType 指定的类型. |
mapper映射文件名有UserDAO.xml/UserMapper.xml/User.xml等几种形式, 其一般存放在与mybatis-configuration.xml同级的mapper目录下,由于其主要作用为定义SQL语句与映射关系, 因此一般统称为mapper映射文件.
/**
* @author jifang
* @since 15/12/31 下午2:27.
*/
public class User {
private Integer id;
private String name;
private String password;
public User() {
}
public User(Integer id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
/**
* @author jifang
* @since 16/2/24 下午6:15.
*/
public class UserDAO {
private SqlSessionFactory factory;
@Before
public void setUp() throws IOException {
String resource = "mybatis/mybatis-configuration.xml";
factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(resource));
}
@Test
public void selectUserById() {
try (SqlSession session = factory.openSession()) {
User user = session.selectOne("namespace.selectUserById", 1);
System.out.println(user);
}
}
@Test
public void selectUserByName() {
try (SqlSession session = factory.openSession()) {
List users = session.selectList("namespace.selectUserByName", "student");
for (User user : users) {
System.out.println(user);
}
}
}
}
id="insertUser" parameterType="com.fq.domain.User">
INSERT INTO user(name, password) VALUES(#{name}, #{password});
@Test
public void insertUser() {
try (SqlSession session = factory.openSession()) {
User user = new User();
user.setName("new_name1");
user.setPassword("new_password");
session.insert("namespace.insertUser", user);
session.commit();
}
}
修改mapper文件,添加
,可以将MySQL的自增主键(即刚刚插入数据时生成的ID)返回:
<insert id="insertUser" parameterType="com.fq.domain.User">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID();
selectKey>
INSERT INTO user(name, password) VALUES(#{name}, #{password});
insert>
属性 | 描述 |
---|---|
keyProperty |
指定存储到DO中的哪个属性; |
order |
selectKey 执行顺序(相对于insert 语句),AFTER /BEFORE ; |
resultType |
主键返回类型(DO中对应属性的类型); |
LAST_INSERT_ID() |
MySQL函数,返回auto_increment自增列新记录值. |
@Test
public void insertUser() {
try (SqlSession session = factory.openSession()) {
System.out.println(session);
User user = new User(null, "new_name", "new_password");
session.insert("namespace.insertUser", user);
// 需要在commit之后才能获得自增主键
session.commit();
System.out.println(user.getId());
}
}
该功能还可以通过
的
useGeneratedKeys
/keyProperty
两个属性合作完成, 详见MyBatis文档.
UPDATE user SET name = #{name}, password = #{password} WHERE id = #{id};
@Test
public void updateUserById() {
try (SqlSession session = factory.openSession(true)) {
session.update("namespace.updateUserById",
new User(1, "feiqing", "ICy5YqxZB1uWSwcVLSNLcA=="));
}
}
<delete id="deleteUserById" parameterType="java.lang.Integer">
DELETE FROM user WHERE id = #{id};
delete>
@Test
public void deleteUserById() {
try (SqlSession session = factory.openSession(true)) {
session.delete("namespace.deleteUserById", 51615);
}
}
#{}
/${}
#{}
: 表示一个占位符号,实现向PreparedStatement
占位符中设置值(#{}
表示一个占位符?
),自动进行Java类型到JDBC类型的转换(因此#{}
可以有效防止SQL注入).#{}
可以接收简单类型或PO属性值,如果parameterType
传输的是单个简单类型值,#{}
花括号中可以是value
或其它名称.${}
: 表示拼接SQL串,通过${}
可将parameterType
内容拼接在SQL中而不进行JDBC类型转换,${}
可以接收简单类型或PO属性值,如果parameterType
传输的是单个简单类型值,${}
花括号中只能是value
. ${}
不能防止SQL注入,但有时${}
会非常方便(如order by
排序,需要将列名通过参数传入SQL,则用ORDER BY ${column}
,使用#{}
则无法实现此功能(详见JDBC基础关于PreparedStatement
的讨论).SqlSession
提供操作数据库的方法(如:selectOne
/selectList
).但SqlSession
是线程不安全的,因此最好将其定义成局部变量使用.
parameterType
自动将Java对象映射至SQL语句.resultType
自动将SQL执行结果映射成Java对象.附: 最好在pom.xml中添加一个日志系统实现(logback/log4j), 这样会在调试程序时打印日志信息,便于查错, 以logback为例:
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-classicartifactId>
<version>1.1.2version>
dependency>
<configuration>
<property name="logRoot" value="/data/logs"/>
<property name="pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{0} - %msg%n"/>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${pattern}pattern>
encoder>
appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${logRoot}/common-server.%d{yyyy-MM-dd}.logfileNamePattern>
<maxHistory>7maxHistory>
rollingPolicy>
<encoder>
<pattern>${pattern}pattern>
encoder>
appender>
<root level="DEBUG">
<appender-ref ref="STDOUT"/>
<appender-ref ref="FILE"/>
root>
configuration>
其他关于MyBatis日志的详细信息可参考MyBatis文档日志部分.
使用MyBatis开发DAO有两个方法,原始DAO开发与Mapper映射DAO开发.
原始DAO开发需要开发人员编写DAO接口与DAO实现,如根据ID查询用户信息:
<select id="selectUserById" parameterType="java.lang.Integer" resultType="com.fq.domain.User">
SELECT * FROM user WHERE id = #{id};
select>
/**
* @author jifang
* @since 16/2/22 上午10:20.
*/
public interface UserDAO {
User selectUserById(Integer id) throws Exception;
}
public class UserDAOImpl implements UserDAO {
private SqlSessionFactory factory;
public UserDAOImpl(SqlSessionFactory factory) {
this.factory = factory;
}
@Override
public User selectUserById(Integer id) throws Exception {
SqlSession session = factory.openSession();
User user = session.selectOne("namespace.selectUserById", id);
session.close();
return user;
}
}
public class MyBatisClient {
@Test
public void originalClient() throws Exception {
UserDAO dao = new UserDAOImpl(new SqlSessionFactoryBuilder().
build(ClassLoader.getSystemResourceAsStream("mybatis/mybatis-configuration.xml")));
User user = dao.selectUserById(1);
System.out.println(user);
}
}
SqlSession
的方法(select
/insert
/update
)需要指定Statement的id,存在硬编码,不利于代码维护.mapper映射开发方法只需编写DAO接口,MyBatis根据接口定义与mapper文件中的SQL语句动态创建接口实现.
<mapper namespace="com.fq.mybatis.UserDAO">
<select id="selectUserById" parameterType="java.lang.Integer" resultType="com.fq.domain.User">
SELECT * FROM user WHERE id = #{id};
select>
mapper>
注意: 此时
namespace
必须与UserDAO
接口的全限定名相同.
UserDAOImpl
/**
* @author jifang
* @since 16/2/22 下午2:57.
*/
public class MyBatisClient {
private SqlSession session;
private SqlSessionFactory factory;
@Before
public void setUp() {
factory = new SqlSessionFactoryBuilder().
build(ClassLoader.getSystemResourceAsStream("mybatis/mybatis-configuration.xml"));
session = factory.openSession();
}
@Test
public void mapperClient() throws Exception {
UserDAO dao = session.getMapper(UserDAO.class);
User user = dao.selectUserById(1);
System.out.println(user);
}
@After
public void tearDown() {
session.close();
}
}
- mapper映射开发方法需要遵循以下规范:
- mapper文件中的namespace与DAO接口的全限定名相同;
- mapper文件中的Statement的id与DAO接口方法名相同;
- mapper文件中的Statement的
parameterType
/resultType
与DAO方法的入参/回参类型相同.
mapper映射文件(如UserDAO.xml)主要作用是定义SQL语句(每个SQL是一个Statement),是MyBatis的核心.
MyBatis官方推荐使用mapper映射的方法来开发DAO,因此我们以后就不再过多介绍原始DAO的开发.
传递简单类型前面示例已经使用过,在此就不再赘述.当需要传递多个形参时,不再需要设置parameterType
参数:
UPDATE user SET name = #{1}, password = #{2} WHERE id = #{0};
void updateUserById(Integer id, String name, String password) throws Exception;
MyBatis使用OGNL表达式解析对象属性值:
<select id="selectUserByNamePassword" parameterType="com.fq.domain.User" resultType="com.fq.domain.User">
SELECT *
FROM user
WHERE name = #{name} AND password = #{password};
select>
User selectUserByNamePassword(User user) throws Exception;
<select id="selectUserByMap" parameterType="java.util.Map" resultType="com.fq.domain.User">
SELECT *
FROM user
WHERE name = #{name} AND password = #{password};
select>
#{}
花括号内对应Map
的key
.
User selectUserByMap(Map<String, Object> map) throws Exception;
<select id="selectUserCount" parameterType="java.lang.String" resultType="java.lang.Integer">
SELECT count(*)
FROM user
WHERE name LIKE '%${value}%';
select>
Integer selectUserCount(String name) throws Exception;
返回简单类型必须保证查询结果只有一行记录,最终将第一个字段的值转换为输出类型.
selectUserById
/selectUserByName
虽然当时使用的是原始DAO开发方法, 但mapper定义形式大同小异),因此在这儿只做简单总结: resultType
是一样的;selectOne
方法调用;selectList
方法调用,接口返回值可用List
/Set
承载.输出PO对象完全可以改用Map
输出,字段名作key,字段值作value.
<select id="selectUserLikeName" resultType="java.util.Map">
SELECT *
FROM user
WHERE name LIKE '%${value}%';
select>
List<Map<String, Object>> selectUserLikeName(String name) throws Exception;
resultType
可将查询结果映射为PO,但前提是PO属性名与SQL字段名必须一致,如不一致,则可通过resultMap
作对应映射:
id="userMap" type="com.fq.domain.User">
<id column="user_id" property="id"/>
<result column="user_name" property="name"/>
<result column="user_password" property="password"/>
属性 | 描述 |
---|---|
|
表示查询结果集的唯一标识; |
|
表示普通结果,即PO属性; |
column |
表示SQL查询出来的字段名, |
property |
表示PO属性. |