Mybatis案例超详解(上)

Mybatis案例超详解

前言:

本来是想像之前一样继续跟新Mybatis,但由于种种原因,迟迟没有更新,快开学了,学了一个暑假,博客也更新了不少,我觉得我得缓缓,先整合一些案例练练,等我再成熟点理解再透彻点之后再详细更新,如果仅仅是为了更新博客而忽视质量的话,有违我的初心,所以我决定,暂时转移路线,整合一些案例,为了以后更新更好的博客而准备。

此篇我会由浅入深进行整理,适合新手练习,希望能对一些有需求的朋友有所帮助。

案例准备

开发工具:IDEA

前端页面:

案例解析

创建Maven项目

Mybatis案例超详解(上)

Mybatis案例超详解(上)

创建数据库

Mybatis案例超详解(上)

Mybatis案例超详解(上)

 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 '备注'
);

  Mybatis案例超详解(上)

Mybatis案例超详解(上)

pom.xml

 <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

 <?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

 <?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

 driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/moocmybatis?useUnicode=true&characterEncoding=utf8
username=root
password=root

  

Mybatis案例超详解(上)

Mybatis案例超详解(上)

Users

 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;
}
}

  

Mybatis案例超详解(上)

Mybatis案例超详解(上)

TestDemo

 
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();
}
}

  

运行结果

Mybatis案例超详解(上)

Mybatis案例超详解(上)

测试成功,证明数据库连接没有任何问题。

Web

Tomcat的配置看我博客园的博客或自己百度搜索

在文章开头的网址中下载并添加整理到如图的文件夹下

Mybatis案例超详解(上)

Mybatis案例超详解(上)

Mybatis案例超详解(上)

Mybatis案例超详解(上)

web.xml

 <?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

 <%@ 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/中学习,在这不多说。

Mybatis案例超详解(上)

Mybatis案例超详解(上)

继续深入

Mybatis案例超详解(上)

Mybatis案例超详解(上)

SqlSessionFactoryUtils

 
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);
}
}
}

  

Mybatis案例超详解(上)

Mybatis案例超详解(上)

UserDao

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;
}
}

  Mybatis案例超详解(上)

InitSqlSessionListener

 
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();
}
}

  

测试(启动服务器,关闭服务器)

Mybatis案例超详解(上)

Mybatis案例超详解(上)

Mybatis案例超详解(上)

Mybatis案例超详解(上)

测试成功。

Mybatis案例超详解(上)

Mybatis案例超详解(上)

UsersFindServlet

 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);
}
}

  

Mybatis案例超详解(上)

Mybatis案例超详解(上)

home.jsp

 <%--
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

 <?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>

  

Mybatis案例超详解(上)

Mybatis案例超详解(上)

index.jsp

 <%@ 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案例超详解(上)

Mybatis案例超详解(上)

Mybatis案例超详解(上)

Mybatis案例超详解(上)

测试成功

好,到这的话Mybatis基础操作入门应该差不多了,此篇到此结束,下一篇会继续更新增删改查功能。

*****************************************************************************************************

我的博客园地址:https://www.cnblogs.com/zyx110/

上一篇:This Gradle plugin requires a newer IDE able to request IDE model level 3. For Android Studio this means v3+


下一篇:xadmin+django2.0删除用户报错,get_deleted_objects() takes 3 positional arguments but 5 were given