spring mybatis增删改查_mybatis注解增删改查

(29) 2024-09-23 11:01:01

目录

一、学习前驱

二、内容主体

1、数据库搭建

3、创建项目(详细步骤和springMVC相同),导入依赖

3、具体功能的实现


一、学习前驱

学习该内容之前首先要了解怎样使用MyBatis和springMVC,不了解的可以浏览博主之前的文章

MyBatis:使用mybatis实现增删改查_ZiXiaFan的博客-CSDN博客

springMVC:idea中使用maven工程搭建SpringMVC框架_ZiXiaFan的博客-CSDN博客

二、内容主体

1、数据库搭建

(1)创建数据库字符集编码改为utf8(例:study),创建数据表,代码方式:(因为管理软件和数据库不同,粘贴复制可能有错,推荐自己手打)

create database 'study' use 'study' create table 'user'( 'id' int (20) not null primary key, 'name' varchar(30) defaukt null, 'pwd' varchar(30) default null )default charset=utf2;

也可以手动方式,数据如下:

spring mybatis增删改查_mybatis注解增删改查 (https://mushiming.com/)  第1张

 (2)向表中添加数据

代码方式:(因为管理软件和数据库不同,粘贴复制可能有错,推荐自己手打)

insert into 'user' ('id','name','pwd')values (1,'fzx','010101'), (2,'zs','010101'), (3,'ls','010101')

 也可以手动方式,数据如下 

spring mybatis增删改查_mybatis注解增删改查 (https://mushiming.com/)  第2张

3、创建项目(详细步骤和springMVC相同),导入依赖

1.项目结构如下图

spring mybatis增删改查_mybatis注解增删改查 (https://mushiming.com/)  第3张

 2.导入依赖

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.fan.ssm</groupId> <artifactId>ssm</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <!-- SpringMVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.1</version> </dependency> <!-- 日志 --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <!-- ServletAPI --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- Spring5和Thymeleaf整合包 --> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.12.RELEASE</version> </dependency> <!--mybatis--> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.2</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> </dependencies> <!-- 在build中配置resource,来防止我们资源导出失败的问题 --> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build> </project>

3.在resources中编写mybatis的核心配置文件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核心配置文件--> <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:3306/study?characterEncoding=utf8"/> <property name="username" value="root"/> <property name="password" value=""/> </dataSource> </environment> </environments> <!-- 每一个Mapper.xml都需要在mybatis核心配置文件中注册 --> <mappers> <mapper resource="com/fan/ssm/mapper/UserMapper.xml"/> </mappers> </configuration>

4.配置web.xml

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--配置编码过滤器--> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceResponseEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--配置处理请求方式put和delete的HiddenHttpMethodFilter--> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--springMVC前端控制器DispatcherServlet--> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springMVC.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>

 5.创建spring配置文件(扫描组件,配置视图解析器)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--扫描组件-->
    <context:component-scan base-package="com.fan.ssm.controller"></context:component-scan>

    <!-- 配置Thymeleaf视图解析器 -->
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">

                        <!-- 视图前缀 -->
                        <property name="prefix" value="/WEB-INF/templates/"/>

                        <!-- 视图后缀 -->
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8" />
                    </bean>
                </property>
            </bean>
        </property>
    </bean>


</beans>

5.在util包下编写MyBatis的工具类,用来获取sqlSession

 

package com.fan.ssm.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; //sqlSessionFactory --> sqlSession public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { //使用mybatis的第一步:获取sqlSessionFactory对象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。 // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。 public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } } 

3、具体功能的实现

ps:本文章主要侧重讲解MyBatis和springMVC,为了不增加学习难度前台页面没有任何渲染样式也没有使用前端框架和js

 1.前端页面

首页(模拟登录页面)index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<form th:action="@{/login}" method="post">
    <table border="0">
        <tr>
            <td>用户名</td>
            <td><input type="text" name="name"></td>
        </tr>
        <tr>
            <td>密码</td>
            <td><input type="password" name="pwd"></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="登录"></td>
        </tr>
        <tr>
            <td colspan="2" align="right"><a th:href="@{/raddUser}">新用户注册</a></td>
        </tr>
    </table>
</form>
</body>
</html>

登录成功的用户主页loginsuccess.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户主页</title>
</head>
<body>
    <table border="1">
        <tr th:each="login:${user}">
            <td><span th:text="${login.name}"></span></td>
            <td><span th:text="${login.pwd}"></span></td>
            <td>
                <a th:href="@{/update(id=${login.id})}">修改</a>
                <a th:href="@{/delete(id=${login.id})}">删除</a>
            </td>
        </tr>
    </table>

</body>
</html>

修改用户信息的主页userUpdate.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>修改用户</title>
</head>
<body>
<form th:action="@{/login}" method="post">
    <input type="hidden" name="id" th:value="${user.id}">
    <table border="1">
        <tr>
            <td>用户名</td>
            <td><input type="text" name="name" th:value="${user.name}"></td>
        </tr>
        <tr>
            <td>密码</td>
            <td><input type="text" name="pwd" th:value="${user.pwd}"></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="提交"></td>
        </tr>
    </table>
</form>
</body>
</html>

添加用户的主页addUser.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>新用户注册</title>
</head>
<body>
<form th:action="@{/addUser}" method="post">
    <table border="0">
        <tr>
            <td>用户名</td>
            <td><input type="text" name="name"></td>
        </tr>
        <tr>
            <td>密码</td>
            <td><input type="password" name="pwd"></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="注册"></td>
        </tr>
    </table>
</form>
</body>
</html>

2.bean包下的User封装类

package com.fan.ssm.bean; public class User { private Integer id; private String name; private String pwd; public User() { } public User(Integer id, String name, String pwd) { this.id = id; this.name = name; this.pwd = pwd; } 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 getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", pwd='" + pwd + '\'' + '}'; } } 

3.mapper包下的mapper接口:UserMaper

package com.fan.ssm.mapper; import com.fan.ssm.bean.User; import java.util.List; public interface UserMapper { /*根据用户名密码查询单个user*/ public User Login(User user); //查询所有用户 public List<User> queryAll(); //根据id查询用户 public User queryOneById(Integer id); //根据id修改用户 public int updateUserById(User user); //根据id删除用户 public int deleteUserById(Integer id); //添加用户 public int addUser(User user); } 

4.配置mapper的配置文件UserMapper.xml文件(编写sql语句的文件)

<?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"> <!--namespace绑定一个对应的dao/mapper接口--> <mapper namespace="com.fan.ssm.mapper.UserMapper"> <select id="Login" resultType="com.fan.ssm.bean.User" parameterType="com.fan.ssm.bean.User"> select * from user where name=#{name} and pwd=#{pwd} </select> <select id="queryAll" resultType="com.fan.ssm.bean.User"> select * from user </select> <select id="queryOneById" resultType="com.fan.ssm.bean.User"> select * from user where id=#{id} </select> <update id="updateUserById" parameterType="com.fan.ssm.bean.User"> update user set name=#{name} , pwd=#{pwd} where id=#{id} </update> <delete id="deleteUserById" parameterType="int"> delete from user where id=#{id} </delete> <insert id="addUser" parameterType="com.fan.ssm.bean.User"> insert into user (name,pwd) values (#{name},#{pwd}); </insert> </mapper>

5.在service层编写业务逻辑类UserService

package com.fan.ssm.service; import com.fan.ssm.bean.User; import com.fan.ssm.mapper.UserMapper; import com.fan.ssm.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import java.util.ArrayList; import java.util.List; public class UserService { //登录 根据name和pwd查询一条 public User login(User user){ SqlSession sqlSession= MybatisUtils.getSqlSession(); UserMapper mapper=sqlSession.getMapper(UserMapper.class); User login = mapper.Login(user); sqlSession.close(); return login; } //查询所有数据 public List<User> queryAll(){ SqlSession sqlSession= MybatisUtils.getSqlSession(); UserMapper mapper=sqlSession.getMapper(UserMapper.class); List<User> list = new ArrayList<User>(); list =mapper.queryAll(); sqlSession.close(); return list; } //根据id查询一条 public User queryOneById(Integer id){ SqlSession sqlSession= MybatisUtils.getSqlSession(); UserMapper mapper=sqlSession.getMapper(UserMapper.class); User user=mapper.queryOneById(id); sqlSession.close(); return user; } //根据id修改用户 public int updateUserById(User user){ Integer res=0; SqlSession sqlSession= MybatisUtils.getSqlSession(); UserMapper mapper=sqlSession.getMapper(UserMapper.class); res=mapper.updateUserById(user); sqlSession.commit(); sqlSession.close(); return res; } //根据id删除用户 public int deleteUserById(Integer id){ Integer res=0; SqlSession sqlSession= MybatisUtils.getSqlSession(); UserMapper mapper=sqlSession.getMapper(UserMapper.class); res=mapper.deleteUserById(id); sqlSession.commit(); sqlSession.close(); return res; } //用户注册 public int addUser(User user){ Integer res=0; SqlSession sqlSession= MybatisUtils.getSqlSession(); UserMapper mapper=sqlSession.getMapper(UserMapper.class); res=mapper.addUser(user); sqlSession.commit(); sqlSession.close(); return res; } } 

6.controller层的UserController,控制页面跳转,前后端连接

package com.fan.ssm.controller; import com.fan.ssm.bean.User; import com.fan.ssm.service.UserService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.ArrayList; import java.util.List; @Controller public class UserController { //登录和查询,根据user的id是否为空判断是根据id查询还是根据用户名密码查询 @RequestMapping("/login") public String login(User user , Model model){ System.out.println(user); UserService service=new UserService(); if(user.getId()==null){ User login = service.login(user); if (login != null){ List<User> userList=new ArrayList<User>(); userList = service.queryAll(); model.addAttribute("user",userList); return "loginsuccess"; } else{ model.addAttribute("failure","failure"); return "index"; } }else { int res=service.updateUserById(user); if(res>0){ List<User> userList=new ArrayList<User>(); userList = service.queryAll(); model.addAttribute("user",userList); return "loginsuccess"; } else { System.out.println("修改失败"); } } return "loginsuccess"; } //修改用户 @RequestMapping("/update") public String uupdate(@RequestParam(value = "id") Integer id, Model model){ UserService service=new UserService(); User user = service.queryOneById(id); model.addAttribute("user",user); return "userUpdate"; } //删除用户 @RequestMapping("/delete") public String delete(@RequestParam(value = "id") Integer id, Model model){ UserService service=new UserService(); Integer res= service.deleteUserById(id); if(res>0){ List<User> userList=new ArrayList<User>(); userList = service.queryAll(); model.addAttribute("user",userList); return "loginsuccess"; }else{ System.out.println("删除失败"); } return "loginsuccess"; } //用户注册 @RequestMapping("/addUser") public String addUser(User user){ UserService service=new UserService(); Integer res= service.addUser(user); if(res>0){ return "index"; }else { System.out.println("注册失败"); } return "index"; } @RequestMapping("/raddUser") public String raddUser(){ return "addUser"; } @RequestMapping("/") public String index(){ return "index"; } } 

分享总结,如有侵权,请联系删除

THE END

发表回复