1.5 SpringBoot 整合Mybatis

说明:
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

此篇是基于以下文章继续创作。
1.1 搭建SpringBoot脚手架
1.2 搭建SpringBoot脚手架注解及标签说明
1.3 SpringBoot 整合热部署
1.4 SpringBoot 整合Thymeleaf

目录

模块 配置项 备注
添加依赖 pom.xml 额外添加mysql及mybatis依赖
配置文件 application.properties 配置文件不允许有多余空格
启动类 App.java 项目启动类
表现层 html 主要负责前台页面的显示
实体层 Entity 存放我们的实体类,与数据库中的属性值基本保持一致
控制层 Controller.java 通过接收前端传过来的参数进行业务操作,在返回一个指定的路径或者数据表
服务层接口 Service.java 在尚未实现具体Service情况下编写上层改代码
服务层实体类 ServiceImpl.java 为控制层提供服务,接受控制层的参数,完成相应的功能,并返回给控制层
持久层接口 Mapper.java 将Mapper.xml中的操作按照id映射成Java函数,供服务层调用
持久层配置文件 Mapper.xml 定义你的功能,对应要对数据库进行的那些操作,比如 insert、selectAll、selectByKey、delete、update等

项目结构

在这里插入图片描述

1. pom.xml文件

<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>org.it</groupId>
  <artifactId>one</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>one</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

	<!--springboot相关jar包版本 也就是说依赖管理,引入以后在申明其它dependency的时候就不需要version了-->
  <parent>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-parent</artifactId>
   <version>1.5.8.RELEASE</version>
  </parent>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    
    <dependency>  
	    <groupId>org.springframework.boot</groupId>  
	    <artifactId>spring-boot-starter-web</artifactId>  
	    <!-- <exclusions>去掉springboot默认配置  
	        <exclusion>  
	            <groupId>org.springframework.boot</groupId>  
	            <artifactId>spring-boot-starter-logging</artifactId>  
	        </exclusion>  
	    </exclusions>   -->
	</dependency> 

    <!-- 设置热启动,修改文件后,服务器自动重启 -->
	<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-devtools</artifactId>
       <optional>true</optional>    
       <scope>runtime</scope>     
	</dependency>
    
    <!-- json解析器和生成器 -->
	<dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.49</version>
    </dependency>
    
        <!-- 配置MyBatis支持 -->
    <dependency>
		<groupId>org.mybatis.spring.boot</groupId>
		<artifactId>mybatis-spring-boot-starter</artifactId>
		<version>1.3.2</version>
	</dependency>

	<!-- 1配置MySQL支持 -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<scope>runtime</scope>
		<version>8.0.11</version>
	</dependency>
    
  </dependencies>
</project>

2. application.properties

# ====================================================================
# ===================\u6570\u636e\u5e93\u8fde\u63a5 \u76f8\u5173\u8bbe\u7f6e============================
# ====================================================================

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/你的数据库名?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=GMT%2B8&useSSL=false

spring.datasource.username=你的用户名

spring.datasource.password=你的密码

# ====================================================================
# ===================mybatis \u76f8\u5173\u8bbe\u7f6e============================
# ====================================================================
mybatis.mapper-locations=classpath:/mapper/*.xml

3. HTML

3.1 list.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
	<head>
		<meta charset="utf-8">
		<title>登记一览表</title>
		<link rel="stylesheet" href="css/font-awesome.min.css" />
		<link rel="stylesheet" href="css/list.css" />
		
		<script src="js/jquery-3.5.1.min.js"></script>
		<script src="js/list.js"></script>
	</head>
	<body>
		
		<h1 align="center">登记一览表</h1>
		
		<form action="/list" method="get">
		<input type="text" name="search" id="search" placeholder="请输入姓名进行模糊查询" />

		<a href="#" onclick="search1()"><i class="fa fa-search" aria-hidden="true"></i></a>
		
		<a id="reregist" href="regist.html" title="返回注册页面" ><i class="fa fa-mail-forward" aria-hidden="true"></i></a>
		<table id="checklist" align="center">

			
			
		</table>
		
		
		</form>
		
	
	</body>
</html>

3.2 regist.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>会员登记表</title>
		<link rel="stylesheet" href="css/regist.css" />
		<link rel="stylesheet" href="css/font-awesome.min.css" />
	
	<script src="js/jquery-3.5.1.min.js"></script>
	<script src="js/regist.js"></script>

		
	</head>
	<body>
		<h1 align="center">会员登记表</h1>
		<div align="center">
			<table align="center">
				<tr>
					<td>姓名:</td>
					<td><input type="text" name="name" id="name" value = "" /></td>
				</tr>
				
				<tr>
					<td>年龄:</td>
					<td><input type="number" name="age" id="age" min="0" max="150" value=""/></td>
				</tr>
				
				<tr>
					<td>爱好:</td>
					<td><input type="checkbox" name="hobby" id="java" value="Java" />Java
						<input type="checkbox" name="hobby" id="c" value="C++" />C++
						<input type="checkbox" name="hobby" id="python" value="Python" />Python
						<input type="checkbox" name="hobby" id="php" value="PHP" />PHP
					</td>
				</tr>
				
				<tr>
					<td>自我介绍:</td>
					<td><textarea name="self" id="self" placeholder="请介绍自己..." value=""></textarea></td>
				</tr>
				
			</table>
			
			<button type="button" name="sub" id="sub">提交</button>
			<button type="button" name="update" id="update">更新</button>&nbsp;&nbsp;
			<button type="button" name="re" id="re">重置</button>
			<br />
			<div style="height: 100px;"></div>
			<a href="list.html">查看一览列表</a><!--  target="_blank" -->
		</div>

		
		
	

	</body>
</html>

CSS及JS文件代码,略

4. User.java

package org.it.one.entity;

public class User {
    
    
	
	private int no;
	
	private String name;
	
	private int age;
	
	private String hobby;
	
	private String self;

	public String getName() {
    
    
		return name;
	}

	public void setName(String name) {
    
    
		this.name = name;
	}

	public int getAge() {
    
    
		return age;
	}

	public void setAge(int age) {
    
    
		this.age = age;
	}

	public String getHobby() {
    
    
		return hobby;
	}

	public void setHobby(String hobby) {
    
    
		this.hobby = hobby;
	}

	public String getSelf() {
    
    
		return self;
	}

	public void setSelf(String self) {
    
    
		this.self = self;
	}

	public int getNo() {
    
    
		return no;
	}

	public void setNo(int no) {
    
    
		this.no = no;
	}
	
	
	
}

5. UserController.java

package org.it.one.controller;

import java.util.ArrayList;
import java.util.List;

import org.it.one.entity.User;
import org.it.one.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

@RestController
public class UserController {
    
    	
	
	@Autowired
	private UserService userService;//定义接口
	
	List<User> list = new ArrayList<User>() ;
	
	
	/**
	 * 保存用户注册信息
	 * @param name
	 * @param age
	 * @param hobby
	 * @param self
	 * @param user
	 */
	@CrossOrigin(origins = "*",maxAge = 3600)
	@RequestMapping("/regist")
	public void regist(@RequestParam("name") String name,
						@RequestParam("age") int age,
						@RequestParam("hobby") String hobby,
						@RequestParam("self") String self,
						User user
						) {
    
    

		List<User>  all = userService.selectAll();
		
		int num= all.size();
		
		int no;
		
		if(num == 0) {
    
    
			no = 1;
		}else {
    
    
			no = all.get(num-1).getNo() + 1;
		}
		
		//hobby

		System.out.println(hobby);
		user.setNo(no);
		user.setName(name);
		user.setAge(age);
		user.setHobby(hobby);
		user.setSelf(self);
		
		userService.regist(user);
		
		no++;

		
	}
	
	
	/**
	 * 一览画面取数据库所有数据
	 * @return
	 */
	@ResponseBody
	@CrossOrigin(origins = "*",maxAge = 3600)
	@RequestMapping("/list")
	public  String list( ) {
    
    
	
		List<User>  all = userService.selectAll();	
		
		String list = JSON.toJSONString(all);
		
		return list;
	}
	
	/**
	 * 删除数据库一条数据
	 * @param index
	 * @return
	 */
	@ResponseBody
	@CrossOrigin(origins = "*",maxAge = 3600)
	@RequestMapping("/del")
	public  String del(@RequestParam("index") int index ) {
    
    
		
		userService.del(index);
		
		return "ok";
	}
	
	/**
	 * 条件查询数据库信息
	 * @param name
	 * @return
	 */
	@ResponseBody
	@CrossOrigin(origins = "*",maxAge = 3600)
	@RequestMapping("/search")
	public  String search(@RequestParam("name") String name  ) {
    
    
	
		List<User>  all = userService.search(name);	
		
		String list = JSON.toJSONString(all);
		
		return list;
	}
	
	
	/**
	 * 修改数据库数据
	 * @param no
	 * @param name
	 * @param age
	 * @param hobby
	 * @param self
	 * @param user
	 */
	@CrossOrigin(origins = "*",maxAge = 3600)
	@RequestMapping("/update")
	public void update( @RequestParam("no") int no,
						@RequestParam("name") String name,
						@RequestParam("age") int age,
						@RequestParam("hobby") String hobby,
						@RequestParam("self") String self,
						User user
						) {
    
    
		
		user.setNo(no);
		user.setName(name);
		user.setAge(age);
		user.setHobby(hobby);
		user.setSelf(self);
		
		userService.update(user);
		
	}
	
	@ResponseBody
	@CrossOrigin(origins = "*",maxAge = 3600)
	@RequestMapping("/select")
	public  String select(@RequestParam("no") int no  ) {
    
    
	
		User user = userService.select(no);	
		
		String one = JSON.toJSONString(user);
		
		return one;
	}
	

}

6. UserService.java

package org.it.one.service;

import java.util.List;

import org.it.one.entity.User;

public interface UserService {
    
    

	public void regist(User user);

	public List<User> selectAll();
	
	public void del(int index);
	
	public List<User> search(String name);

	public void update(User user);

	public User select(int no);
}

7. UserServiceImpl.java

package org.it.one.serviceImpl;

import java.util.List;

import org.it.one.dao.UserMapper;
import org.it.one.entity.User;
import org.it.one.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
    
    
	
	@Autowired
	private UserMapper userMapper;

	@Override
	public void regist(User user) {
    
    
		// TODO Auto-generated method stub
		
		userMapper.regist(user);	
		
	}
	
	public List<User> selectAll() {
    
    
		
		List<User> all = userMapper.selectAll();
		
		return all;
		 
	}
	

	@Override
	public void del(int no) {
    
    
		// TODO Auto-generated method stub
		
		userMapper.del(no);
		
	}

	@Override
	public List<User> search(String name) {
    
    
		
		List<User> all = userMapper.search(name);
		
		return all;
	}

	@Override
	public void update(User user) {
    
    
		// TODO Auto-generated method stub
		userMapper.update(user);
	}

	@Override
	public User select(int no) {
    
    
		// TODO Auto-generated method stub
		return	userMapper.select(no);
		
	}
	
	
}

8. UserMapper.java

package org.it.one.dao;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.it.one.entity.User;
@Mapper
public interface UserMapper {
    
    

	public void regist(User user);

	public List<User> selectAll();

	public void del(int no);
	
	public List<User> search(String name);

	public void update(User user);

	public User select(int no);
}

9. UserMapper.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="org.it.one.dao.UserMapper" >

	<resultMap id="BaseResultMap" type="org.it.one.entity.User" >
	    <id column="no" property="no" jdbcType="INTEGER" />
	    <result column="no" property="no" jdbcType="INTEGER" />
	     <result column="name" property="name" jdbcType="VARCHAR" />
	    <result column="age" property="age" jdbcType="INTEGER" />
	    <result column="hobby" property="hobby" jdbcType="VARCHAR" />
	    <result column="self" property="self" jdbcType="VARCHAR" />	    
	</resultMap>
	
	<insert id="regist" parameterType="org.it.one.entity.User" >
	    insert into users ( no, name, age, hobby, self)
	    values (#{no, jdbcType=INTEGER},
	    		#{name, jdbcType=VARCHAR},
	    		#{age, jdbcType=INTEGER},
	    		#{hobby, jdbcType=VARCHAR},
	    		#{self, jdbcType=VARCHAR}
	    	    )
	</insert>

	<select id="selectAll" parameterType="org.it.one.entity.User" resultType="org.it.one.entity.User">
		select * from users 
	</select>
	
	<delete id="del" parameterType="INTEGER">
			delete from users 
			where no=#{no}
	</delete>
	
	<select id="search" parameterType="string" resultType="org.it.one.entity.User">
	    select *
	    from users
	    <where>	
			<if test="_parameter!= null and _parameter!= ''">
				name like concat('%', #{name}, '%')
			</if>
		</where>
 	</select>
	
	<update id="update"  parameterType="org.it.one.entity.User">
		update users set name=#{name}, age=#{age}, hobby=#{hobby}, self=#{self}  
		where no=#{no}
	</update>
	
	<select id="select" parameterType="INTEGER" resultType="org.it.one.entity.User">
		select * from users where no=#{no}
	</select>

		
</mapper>

10. 案例及源码

基于以上代码实现的页面截图,如下:
在这里插入图片描述
在这里插入图片描述
源码:
1.5 前台HTML代码
1.5 后台Springboot源码

猜你喜欢

转载自blog.csdn.net/qq_40805441/article/details/112853425