Mybatis入门详解及案例
前言:
本来是想像之前一样继续跟新Mybatis,但由于种种原因,迟迟没有更新,快开学了,学了一个暑假,博客也更新了不少,我觉得我得缓缓,先整合一些案例练练,等我再成熟点理解再透彻点之后再详细更新,如果仅仅是为了更新博客而忽视质量的话,有违我的初心,所以我决定,暂时转移路线,整合一些案例,为了以后更新更好的博客而准备。
案例准备
开发工具:IDEA
前端页面:
-
在Bootstrap官网https://getbootstrap.com/下载 Bootstrap CSS、JavaScript 和字体的预编译的压缩版本
-
从 jquery.com 下载 jQuery 库
案例解析
创建Maven项目
创建数据库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | CREATE DATABASE moocmybatis; USE moocmybatis; CREATE TABLE users( id INT AUTO_INCREMENT PRIMARY KEY COMMENT '用户编号' , username VARCHAR( 50 ) NOT NULL COMMENT '登录账号' , userpass VARCHAR( 50 ) NOT NULL COMMENT '登录密码' , nickname VARCHAR( 50 ) COMMENT '昵称' , age INT COMMENT '用户年龄' , gender VARCHAR( 5 ) COMMENT '用户性别' , phone VARCHAR( 13 ) COMMENT '联系方式' , email VARCHAR( 20 ) COMMENT '用户邮箱' , createTime DATETIME COMMENT '账号创建时间' , updateTime DATETIME COMMENT '账号最后修改时间' , lastLogin DATETIME COMMENT '账号最后一次登录时间' , userStatus INT COMMENT '用户账号的状态 0 正常 1 锁定 2 删除' , remark TEXT COMMENT '备注' ); |
pom.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 25 26 27 28 | <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version> 3.4 . 6 </version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version> 5.1 . 38 </version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version> 3.1 . 0 </version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version> 1.2 </version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version> 4.12 </version> <scope>test</scope> </dependency> </dependencies> |
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 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | <?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 主要用于进行数据源的配置 可以配置多个数据源~ 通过 default 属性来指定当前项目运行过程中使用的是哪个数据源 --> <environments default = "development" > <!-- environment 用于配置一个具体的独立的数据源 id属性用于给当前数据源定义一个名称,方便我们的项目指定 --> <environment id= "development" > <!-- transactionManager用于配置事务管理,默认情况下使用的是JDBC事务管理 --> <transactionManager type= "JDBC" /> <!-- dataSource具体数据源的链接信息;type属性用于指定是否使用连接池 --> <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主要用于配置我们外部的映射配置文件 在主配置文件中需要引入加载映射配置文件 --> <mappers> <!-- mapper主要配置引入某一个具体的映射文件,resource进行路径方式的引入 --> <mapper resource= "mapper/usersMapper.xml" /> </mappers> </configuration> |
usersMapper.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?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.demo.entity.Users" > <select id= "usersList" resultType= "com.demo.entity.Users" > select * from users; </select> </mapper> |
db.properties
1 2 3 4 | driver=com.mysql.jdbc.Driver url=jdbc:mysql: //localhost:3306/moocmybatis?useUnicode=true&characterEncoding=utf8 username=root password=root |
Users
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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | package com.demo.entity; import java.util.Date; public class Users { private Integer id; // 用户编号 private String username; // 登录账号 private String userpass; // 登录密码 private String nickname; // 用户昵称 @Override public String toString() { return "Users{" + "id=" + id + ", username='" + username + '\ '' + ", userpass='" + userpass + '\ '' + ", nickname='" + nickname + '\ '' + '}' ; } 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 getUserpass() { return userpass; } public void setUserpass(String userpass) { this .userpass = userpass; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this .nickname = nickname; } } |
TestDemo
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 | import com.demo.entity.Users; 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.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; public class TestDemo { @Test public void test1() throws IOException { String resource = "mybatis-config.xml" ; InputStream is = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession session= sqlSessionFactory.openSession(); List<Users> list = session.selectList( "usersList" ); for (Users user:list){ System.out.println(user); } session.close(); } } |
运行结果
测试成功,证明数据库连接没有任何问题。
Web
Tomcat的配置看我博客园的博客或自己百度搜索
在文章开头的网址中下载并添加整理到如图的文件夹下
web.xml
1 2 3 4 5 6 7 8 9 10 11 12 | <?xml version= "1.0" encoding= "UTF-8" ?> <web-app xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns= "http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation= "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id= "WebApp_ID" version= "3.1" > <display-name>mybatispro</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> |
index.jsp
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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | <%@ page contentType= "text/html;charset=UTF-8" language= "java" %> <html> <head> <title>用户管理中心</title> <link rel= "stylesheet" href= "lib/bootstrap-3.3.7-dist/css/bootstrap.min.css" > <script src= "lib/2.2.4/jquery-1.12.4.min.js" ></script> <script src= "lib/bootstrap-3.3.7-dist/js/bootstrap.min.js" ></script> </head> <body> <div class = "container" > <div class = "row" > <div class = "page-header" > <h1>泰斗贤若如后台管理系统 <small>用户数据管理中心</small></h1> </div> </div> <div class = "row" > <div class = "jumbotron" > <h1>MyBatis基础入门!</h1> <p>通过一个项目来完成基础部分的学习</p> <p><a class = "btn btn-primary btn-lg" href= "#" role= "button" >请关注泰斗贤若如博客园</a></p> <p><a class = "btn btn-primary btn-lg" href= "#" role= "button" >新增用户</a></p> </div> </div> <div class = "row" > <table class = "table table-hover table-striped" > <tr> <th>用户编号</th> <th>登录账号</th> <th>用户昵称</th> <th>邮箱</th> <th>联系方式</th> <th>账号创建时间</th> <th>用户状态</th> <th>操作</th> </tr> <tr> <td> 111 </td> <td>张三丰</td> <td>拉拉</td> <td> 222 @qq .com</td> <td> 244465656 </td> <td> 2019 </td> <td>正常</td> <td> <a href= "#" >查看</a> <a href= "#" >修改</a> <a href= "#" >删除</a> </td> </tr> <tr> <td> 111 </td> <td>张三丰</td> <td>拉拉</td> <td> 222 @qq .com</td> <td> 244465656 </td> <td> 2019 </td> <td>正常</td> <td> <a href= "#" >查看</a> <a href= "#" >修改</a> <a href= "#" >删除</a> </td> </tr> <tr> <td> 111 </td> <td>张三丰</td> <td>拉拉</td> <td> 222 @qq .com</td> <td> 244465656 </td> <td> 2019 </td> <td>正常</td> <td> <a href= "#" >查看</a> <a href= "#" >修改</a> <a href= "#" >删除</a> </td> </tr> </table> </div> </div> </body> </html> |
启动服务器并展示页面
Bootstrap的学习可以到https://v3.bootcss.com/中学习,在这不多说。
继续深入
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 38 39 40 41 42 43 44 | package com.demo.utils; 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 SqlSessionFactoryUtils { private static String RESOURCE = "mybatis-config.xml" ; private static SqlSessionFactory sqlSessionFactory; private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>(); /** * 创建一个初始化SqlSessionFactory的方法 */ public static void initSqlSessionFactory(){ try { InputStream is = Resources.getResourceAsStream(RESOURCE); sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); } catch (IOException e) { e.printStackTrace(); } } /** * 获取工厂的方法 * @return */ public static SqlSessionFactory getSqlSessionFactory(){ return sqlSessionFactory; } public static void close(){ SqlSession session = threadLocal.get(); if (session!= null ){ session.close(); threadLocal.set( null ); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package com.demo.dao; import com.demo.entity.Users; import com.demo.utils.SqlSessionFactoryUtils; import org.apache.ibatis.session.SqlSession; import java.util.List; public class UsersDao { private SqlSession session = SqlSessionFactoryUtils.getSqlSessionFactory().openSession(); private List<Users> list; public List<Users> findAll(){ try { list = session.selectList( "findAll" ); } catch (Exception e){ e.printStackTrace(); } finally { session.close(); } return list; } } |
InitSqlSessionListener
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package com.demo.listener; import com.demo.utils.SqlSessionFactoryUtils; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; @WebListener public class InitSqlSessionListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { System.out.println( "容器加载中。。。。。" ); //初始化SqlSessionFactory对象 SqlSessionFactoryUtils.initSqlSessionFactory(); } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { System.out.println( "容器销毁中。。。。。" ); //关闭SqlSession对象 SqlSessionFactoryUtils.close(); } } |
测试(启动服务器,关闭服务器)
测试成功。
UsersFindServlet
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 | package com.demo.servlet; import com.demo.dao.UsersDao; import com.demo.entity.Users; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @WebServlet ( "/index" ) public class UsersFindServlet extends HttpServlet { private UsersDao usersDao = new UsersDao(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 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); } } |
home.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <%-- Created by IntelliJ IDEA. User: Lenovo Date: 2019 / 8 / 16 Time: 9 : 21 To change this template use File | Settings | File Templates. --%> <%@ page contentType= "text/html;charset=UTF-8" language= "java" %> <html> <head> <title>跳转</title> </head> <body> <% response.sendRedirect( "/index" ); %> </body> </html> |
web.xml
1 2 3 4 5 6 7 8 9 10 11 12 | <?xml version= "1.0" encoding= "UTF-8" ?> <web-app xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns= "http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation= "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id= "WebApp_ID" version= "3.1" > <display-name>mybatispro</display-name> <welcome-file-list> <welcome-file>home.jsp</welcome-file> </welcome-file-list> </web-app> |
index.jsp
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 39 40 41 42 43 44 45 46 47 48 49 50 51 | <%@ page contentType= "text/html;charset=UTF-8" language= "java" %> <%@ taglib prefix= "c" uri= "http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix= "fmt" uri= "http://java.sun.com/jsp/jstl/fmt" %> <html> <head> <title>用户管理中心</title> <link rel= "stylesheet" href= "lib/bootstrap-3.3.7-dist/css/bootstrap.min.css" > <script src= "lib/2.2.4/jquery-1.12.4.min.js" ></script> <script src= "lib/bootstrap-3.3.7-dist/js/bootstrap.min.js" ></script> </head> <body> <div class = "container" > <div class = "row" > <div class = "page-header" > <h1>泰斗贤若如后台管理系统 <small>用户数据管理中心</small></h1> </div> </div> <div class = "row" > <div class = "jumbotron" > <h1>MyBatis基础入门!</h1> <p>通过一个项目来完成基础部分的学习</p> <p><a class = "btn btn-primary btn-lg" href= "#" role= "button" >请关注泰斗贤若如博客园</a></p> <p><a class = "btn btn-primary btn-lg" href= "#" role= "button" >新增用户</a></p> </div> </div> <div class = "row" > <table class = "table table-hover table-striped" > <tr> <th>用户编号</th> <th>登录账号</th> <th>用户密码</th> <th>用户昵称</th> </tr> <c:forEach var= "user" items= "${usersList}" > <tr> <td>${user.id}</td> <td>${user.username}</td> <td>${user.userpass}</td> <td>${user.nickname}</td> <td> <a href= "#" >查看</a> <a href= "#" >修改</a> <a href= "#" >删除</a> </td> </tr> </c:forEach> </table> </div> </div> </body> </html> |
开启服务器测试
测试成功
好,到这的话Mybatis基础操作入门应该差不多了,此篇到此结束,下一篇会继续更新增删改查功能。
*****************************************************************************************************
我的博客园地址:https://www.cnblogs.com/zyx110/

作者:泰斗贤若如
微信公众号:去有风的地方飞翔
Github:https://github.com/zyx110
有事微信:zyxt1637039050
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。

我不能保证我所说的都是对的,但我能保证每一篇都是用心去写的,我始终认同: “分享的越多,你的价值增值越大”,我们一同在分享中进步,在分享中成长,越努力越幸运。再分享一句话“十年前你是谁,一年前你是谁,甚至昨天你是谁,都不重要。重要的是,今天你是谁,以及明天你将成为谁。”
人生赢在转折处,改变从现在开始!
支持我的朋友们记得点波推荐哦,您的肯定就是我前进的动力。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?