前言
工作这么多年,ORM框架一直选择Mybatis框架。 Mybatis的使用方式也一直在变,总体来说是越来越简单。写篇文章对各使用方式做个总结...
正文
一、Mybatis典型用法
1. 正常执行流程
♦ 配置文件 - 全局配置信息和映射文件信息。全局配置信息包括:数据库配置和事务配置。映射文件就是SQL相关的
♦ Mybatis读取配置文件生成SqlSessionFactory,即回话工厂
♦ 获取SqlSession, 做CRUD操作。但真正做这个事情的是底层的executor。
♦ Executor执行器把SQL分装到MappedStatement对象中。该对象包括:SQL, 输入参数映射信息和输出结果映射信息。
2. 案例
2.1 建表
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(20) , `password` varchar(20) , `age` int(11) , PRIMARY KEY (`id`) )
2.2 全局配置文件
<?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:3307/book"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mybatis/User.xml"/> </mappers> </configuration>
2.3 mapper.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="user"> <select id="findUserById" parameterType="int" resultType="com.mybatis.User"> select * from user where id = #{id} </select> <select id="findUserAll" resultType="com.mybatis.User"> select * from user </select> <insert id="insertUser" parameterType="com.mybatis.User"> insert into user(username,password,age) values(#{username},#{password},#{age}) </insert> <delete id="deleteUserById" parameterType="int"> delete from user where id=#{id} </delete> <update id="updateUserPassword" parameterType="com.mybatis.User"> update user set password=#{password} where id=#{id} </update> </mapper>
2.4 Dao 接口
package com.mybatis.dao; import com.mybatis.User; import java.util.List; public interface UserDao { public User findUserById(int id) throws Exception ; public List<User> findAllUsers() throws Exception; public void insertUser(User user) throws Exception; public void deleteUserById(int id) throws Exception; public void updateUserPassword(User user) throws Exception; }
2.5 DaoImpl
package com.mybatis.dao.impl; import com.mybatis.User; import com.mybatis.dao.UserDao; 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; import java.util.List; public class UserDaoImpl implements UserDao { private static SqlSessionFactory factory = null; static { String resource = "mybatis/SqlMapConfig.xml"; InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(resource); } catch (IOException e) { e.printStackTrace(); } factory = new SqlSessionFactoryBuilder().build(inputStream); } public static SqlSession getSession(){ return factory.openSession(); } @Override public User findUserById(final int id) throws Exception { return getSession().selectOne("user.findUserById",id); } @Override public List<User> findAllUsers() throws Exception { return null; } @Override public void insertUser(final User user) throws Exception { } @Override public void deleteUserById(final int id) throws Exception { } @Override public void updateUserPassword(final User user) throws Exception { } }
2.6 User类
package com.mybatis; import lombok.Data; @Data public class User { private Integer id; private String username; private String password; private Integer age; }
2.7 测试类
package com.mybatis.dao; import com.mybatis.User; import com.mybatis.dao.impl.UserDaoImpl; import org.junit.Test; public class UserDaoTest { @Test public void testFindUserById() throws Exception{ UserDao userDao = new UserDaoImpl(); User user = userDao.findUserById(7); System.out.println(user); } }
二、Mapper代理开发方式
Mapper代理的开发方式,我们只需要编写mapper接口,不需要再Dao类,MyBatis会为我们生成代理类。代理开发方式应当遵循以下条件:
♦ mapper接口的全限定名要和mapper映射文件的namespace的值相同。
♦ mapper接口的方法名称要和mapper映射文件中的statement的id相同。
♦ mapper接口的方法参数只能有一个,且类型要和mapper映射文件中statement的parameterType的值保持一致。
♦ mapper接口的返回值类型要和mapper映射文件中statement的resultType值或resultMap中的type值保持一致。
案例:
1. 建表 同2.1
2. 全局配置 同2.2
3. mapper.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.mybatis2.dao.UserDao"> <select id="findUserById" parameterType="int" resultType="com.mybatis2.User"> select * from user where id = #{id} </select>
<select id="findUserAll" resultType="com.mybatis2.User">
select * from user
</select>
<insert id="insertUser" parameterType="com.mybatis.User">
insert into user(username,password,age) values(#{username},#{password},#{age})
</insert>
<delete id="deleteUserById" parameterType="int">
delete from user where id=#{id}
</delete>
<update id="updateUserPassword" parameterType="com.mybatis.User">
update user set password=#{password} where id=#{id}
</update>
</mapper>
4.mapper类:类名无所谓,用*Dao或者*Mapper都可以
package com.mybatis2.dao; import com.mybatis2.User; import java.util.List; public interface UserDao {
public User findUserById(int id) throws Exception ;
public List<User> findUserAll() throws Exception;
public void insertUser(User user) throws Exception;
public void deleteUserById(int id) throws Exception;
public void updateUserPassword(User user) throws Exception;
}
5. User类同2.5
6. 测试类
package com.mybatis.dao;
import com.mybatis2.dao.UserDao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
public class UserDaoTest2 {
private static SqlSessionFactory factory = null;
@BeforeClass
public static void init(){
String resource = "mybatis/SqlMapConfig.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
factory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void testFindUserById() throws Exception{
UserDao mapp = factory.openSession().getMapper(UserDao.class);
System.out.println(mapp.findUserById(7));
}
}
三、与Spring框架的集成
相关背景,使用方式官方文档已经很详细了。参考官方文档 - http://www.mybatis.org/spring/