1.概述

  • MyBatis是支持定制化SQL、存储过程以及高级映射的优秀持久层框架

    1. 避免传统JDBC硬编码

    2. XML配置或者注解

    3. POJO对象和数据库记录直接映射

    4. 完善的文档支持

  • MyBatis使用场景

    1. 更加关注SQL优化的项目

    2. 需求频繁更新改动的项目

2.开发环境搭建(以User实体类为例)

  • 安装(maven中添加依赖到pom.xml)

    1
    2
    3
    4
    5
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>版本号</version>
    </dependency>

    若要使用数据库

    1
    2
    3
    4
    5
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.41</version>
    </dependency>
  • 在resources文件中添加mybatis-config.xml配置文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    <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配置 用于加载外部的properties配置文件-->
    <properties resource="db.properties"></properties>
    <!--environments 主要用于数据源的配置,可以配置多个数据源-->
    <environments default="development">
    <environment id="development">
    <transactionManager type="JDBC"/>
    <dataSource type="POOLED">
    <property name="driver" value="${driver}"/>
    <property name="url" value="${url}"/>
    <property name="username" value="${username}"/>
    <property name="password" value="${password}"/>
    </dataSource>
    </environment>
    </environments>
    <mappers>
    <!--引入某一个具体的映射文件,resource进行路径方式引入 -->
    <mapper resource="mapper/usersMapper.xml"/>
    </mappers>
    </configuration>

    db.properties文件中:

    1
    2
    3
    4
    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/mydb
    username=root
    password=

    usersMapper.xml配置文件中:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    <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属性是用来配置命名空间,主要进行session级别的缓存管理
    命名空间默认情况下,使用我们当前操作的实体类的全路径
    -->
    <mapper namespace="com.imooc.entity.Users">

    <!-- <select id = "findById" resultType="com.imooc.entity.Users">
    SELECT * FROM users where id = #{ id }
    </select> -->

    <select id = "findAll" resultType="com.imooc.entity.Users">
    SELECT * FROM users
    <if test="id != null">
    where id = #{id}
    </if>
    </select>
    </mapper>

3.utils类 - SqlSessionFactoryUtils

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class SqlSessionFactoryUtils {
private static String RESOURCE = "mybatis-config.xml";

private static SqlSessionFactory sqlSessionFactory;

//将SqlSessionFactory对象存放在ThreadLocal进行管理
private static ThreadLocal<SqlSessionFactory> threadLocal = new ThreadLocal<SqlSessionFactory>();

/*
初始化SqlsessionFactory方法
*/
public static void initSqlSessionFactory(){
try{
InputStream is = Resources.getResourceAsStream(RESOURCE);

sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
}catch(IOException e){
e.printStackTrace();
}
}
/*
获取工厂对象方法
*/
public static SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
/*
关闭Sqlsession方法
*/
public static void close(){
SqlSession session = (SqlSession) threadLocal.get();
if(session != null){
session.close();
threadLocal.set(null);
}
}
}

4.dao类 - UsersDAO

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class UsersDAO {
//执行查询操作 获取数据
private SqlSession sqlSession ;
private List<Users> list;
private Users user;

private SqlSession getSqlSession(){
sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
return sqlSession;
}
/*
全部数据查询
*/

public List<Users> findAll(){
try{
list = getSqlSession().selectList("findAll");
}catch(Exception e){
e.printStackTrace();
}finally{
sqlSession.close();
}
return list;
}
/*
根据编号查询
*/
public Users findById(@Param("id")Integer id){
try{
user = getSqlSession().selectOne("findById",id);
}catch(Exception e){
e.printStackTrace();
}finally{
sqlSession.close();
}
return user;
}
}

5.servlet类 - 多条数据查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@WebServlet("/index")
public class UsersFindServlet extends HttpServlet {
private UsersDAO usersDAO = new UsersDAO();

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<Users> list = usersDAO.findAll();
req.setAttribute("usersList",list);
req.getRequestDispatcher("index.jsp").forward(req,resp);
}
}

6.servlet类 - 单条数据查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@WebServlet("/detail")
public class UsersFindByIdServlet extends HttpServlet {
private UsersDAO usersDAO = new UsersDAO();

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
Users user = usersDAO.findById(Integer.parseInt(id));
req.setAttribute("user",user);
req.getRequestDispatcher("detail.jsp").forward(req,resp);
}
}

7.listener类 - 初始化Listener

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//监听器 监听容器启动和销毁
@WebListener //注解配置 监听器注册到容器中
public class InitSqlSessionListener implements ServletContextListener {

public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("容器加载中...");
//初始化SqlSessionFactory对象
SqlSessionFactoryUtils.initSqlSessionFactory();
}

public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("容器销毁中...");
//关闭SqlSession对象
SqlSessionFactoryUtils.close();
}
}