springboot+springmvc+mybatis整合及CRUD簡單示例

整體項目結構

首先新建一可以正常啓動spring boot項目

https://blog.csdn.net/qq_43560721/article/details/104653470

pom.xml配置

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.xxs</groupId>
    <artifactId>ssmcrud</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>ssmcrud</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- spring boot 啓動器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- mybatis啓動器 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- mysql數據庫驅動 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!-- druid數據庫連接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

配置數據庫連接信息及其他配置

application.properties或application.yml(兩種任選其一即可)

application.properties



spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

mybatis.type-aliases-package=cn.xxs.ssmcrud.pojo
mybatis.configuration.map-underscore-to-camel-case=true

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm?serverTimezone=GMT%2B8&characterEncoding=utf8
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource


mybatis:
  type-aliases-package: cn.xxs.ssmcrud.pojo
  configuration.map-underscore-to-camel-case: true

創建數據庫表

create table user(
	 id int primary key auto_increment,
	 name varchar(16) unique not null,
	 pwd varchar(16) not null,
	 createDate datetime
	 );
insert into user values(1,'王五',123,now());
insert into user values(2,'奧特曼',123,null);
insert into user values(4,'mary',123,null);

創建User類

package cn.xxs.ssmcrud.pojo;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;


public class User {
    private Integer id;
    private String name;
    private String pwd;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date createDate;
    public User() {
        super();
        // TODO Auto-generated constructor stub
    }
    public User(Integer id, String name, String pwd, Date createDate) {
        super();
        this.id = id;
        this.name = name;
        this.pwd = pwd;
        this.createDate = createDate;
    }
    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;
    }

//    @JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", pwd=" + pwd + ", createDate=" + createDate + "]";
    }

}

創建UserMapper接口

這裏有兩種方式(可用映射文件,可用註解,我用的註解方式,所以這裏映射文件就簡單舉例了)

映射文件方法

public interface UserMapper {

	/**
	 * 查詢所有用戶信息
	 * @return
	 */
	public List<User> selectUsers();
	
	/**
	 * 添加用戶信息
	 */
	public void insertUser(User user);
}
<?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:命名空間
 -->  
<mapper namespace="com.hp.mapper.UserMapper">

  <!-- 查詢所有用戶信息 -->
   <select id="selectUsers" resultType="user">
    	select 
			*
			from user u 
  </select>

  <!-- 添加用戶信息 -->
  <insert id="insertUser" parameterType="user">
  		insert into 
  		user(name,pwd,createDate)
  		values(#{name},#{pwd},#{createDate})
  </insert>
  
</mapper>

註解方式

package cn.xxs.ssmcrud.mapper;
import java.util.List;

import cn.xxs.ssmcrud.pojo.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

public interface UserMapper {
    /**
     * 查詢所有用戶信息
     * @return
     */
    @Select("select * from user")
    public List<User> selectUsers();

    /**
     * 添加用戶信息
     */
    @Insert("insert into user(name,pwd,createDate)values(#{name},#{pwd},#{createDate})")
    public void insertUser(User user);

    /**
     * 查詢用戶信息
     * @return
     */
    @Select("select * from user where id=#{id}")
    public User selectUserByUserId(Integer id);

    /**
     * 更新用戶信息
     */
    @Update("update user set name = #{name},pwd = #{pwd} where id = #{id}")
    public void updateUser(User user);

    /**
     * 根據id刪除用戶信息
     */
    @Delete("delete from user where id=#{id}")
    public void deleteUserByUserId(Integer id);
}

創建service層接口

package cn.xxs.ssmcrud.service;

import cn.xxs.ssmcrud.pojo.User;

import java.util.List;

public interface UserService{
	/**
	 * 查詢所有用戶信息
	 * @return
	 */
	public List<User> selectUsers();

	/**
	 * 添加用戶信息
	 */
	public void insertUser(User user);

	/**
	 * 查詢用戶信息
	 * @return
	 */
	public User selectUserByUserId(Integer id);

	/**
	 * 更新用戶信息
	 */
	public void updateUser(User user);

	/**
	 * 根據Id刪除用戶信息
	 */
	public void deleteUserById(Integer id);
}

創建service層接口的實現類

package cn.xxs.ssmcrud.service.impl;
import java.util.List;

import javax.annotation.Resource;

import cn.xxs.ssmcrud.mapper.UserMapper;
import cn.xxs.ssmcrud.pojo.User;
import cn.xxs.ssmcrud.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 查詢所有用戶信息
     * @return
     */
    public List<User> selectUsers(){

        return userMapper.selectUsers();
    }

    /**
     * 添加用戶信息
     */
    public void insertUser(User user) {

        userMapper.insertUser(user);
    }


    /**
     * 查詢用戶信息
     * @return
     */
    public User selectUserByUserId(Integer id) {

        return userMapper.selectUserByUserId(id);
    }

    /**
     * 更新用戶信息
     */
    public void updateUser(User user) {
        userMapper.updateUser(user);
    }

    @Override
    public void deleteUserById(Integer id) {
        userMapper.deleteUserByUserId(id);
    }
}

創建UserController類

package cn.xxs.ssmcrud.controller;
import java.util.List;

import javax.annotation.Resource;

import cn.xxs.ssmcrud.pojo.User;
import cn.xxs.ssmcrud.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("")
public class UserController{

    @Resource
    private UserService userService;

    /**
     * 進入首首頁
     */
    @RequestMapping(value="index")
    public String index() {
        return "index";
    }

    /**
     * 查詢所有用戶信息
     */
    @RequestMapping(value="userInfo")
    public String userInfo(ModelMap map) {

        List<User> userList = userService.selectUsers();
        map.put("userList", userList);

        return "userInfo";
    }
    /**
     * 進入新增頁面
     * @param map
     * @return
     */
    @RequestMapping(value="userEdit")
    public String userEdit(Integer id,ModelMap map) {

        if(id!=null) {
            //根據id查詢用戶信息
            User user = userService.selectUserByUserId(id);
            map.put("user", user);
            map.put("id", id);
        }else {
            map.put("user", new User());
        }

        return "userEdit";
    }

    /**
     * 保存和更新用戶信息
     */
    @RequestMapping(value="addUser")
    public String addUser(Integer id,User user,ModelMap map) {
        if(id!=null) {
            userService.updateUser(user);
        }else {
            userService.insertUser(user);
        }
        return "redirect:userInfo";
    }
    /**
     * 刪除用戶信息
     */
    @RequestMapping(value="userDelete")
    public String userDelete(Integer id) {

        userService.deleteUserById(id);

        return "redirect:userInfo";
    }
    /**
     * 測試ajax
     * @return
     */
    @RequestMapping("test")
    @ResponseBody
    public String testAjax() {
        int i = 1;
        if (i == 1) {
            return "success";
        } else {
            return "error";
        }
    }
}

創建新增用戶和修改用戶信息頁面UserEdit.html

<!DOCTYPE html>
<html  xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>新增用戶</title>
<script type="text/javascript" src="/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
	$(function(){
		var id = $('#id').val();
		if(id!=""){
			$('#createDate').attr("readonly","readonly");
		}
	})
</script>
</head>
<body>
	<form th:action="@{/addUser}" method="post">
		用戶姓名:<input type="text" name="name" th:value="${user.name}" /><br>
		用戶密碼:<input type="text" name="pwd" th:value="${user.pwd}" /><br>
		創建日期:<input type="date" id="createDate" name="createDate" th:value="${#dates.format(user.createDate,'yyyy-MM-dd')}" /><br>
		<input type="submit" value="保存" /><br>
		<input type="hidden" id="id" name="id" th:value="${id}" />
	</form>
</body>
</html>

創建顯示列表頁面userInfo.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a th:href="@{/userEdit}">新增用戶</a>	
<table border="1" align="center" width="50%">
	<thead>
		<tr>
			<th>用戶編號</th>
			<th>用戶姓名</th>
			<th>用戶密碼</th>			
			<th>創建日期</th>
			<th>操作</th>
		</tr>
	</thead>
	<tbody>
		<tr th:each="user: ${userList}">
			<td th:text=${user.id}></td>
			<td th:text=${user.name}></td>
			<td th:text=${user.pwd}></td>
			<td th:text="${#dates.format(user.createDate,'yyyy-MM-dd')}"></td>
			<td><a th:href="@{/userEdit(id=${user.id})}">更新</a><a th:href="@{/userDelete(id=${user.id})}">刪除</a></td>
		</tr> 
	</tbody>
</table>
</body>
</html>

創建首頁index.html(這裏包含了一個ajax異步校驗)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>主頁</title>
<script type="text/javascript" src="/jquery-3.3.1.min.js"></script>
</head>
<body>	
	<a th:href="@{/userInfo}">用戶列表</a>	<br>
	<a style="cursor: pointer;" onclick="TestAjax()">測試ajax</a>
	<script type="text/javascript">
		function TestAjax() {
			$.ajax({
				url : "test",
				type : "post",
				dataType : "text",
				success : function(data) {
					if (data == "success") {
						alert("測試成功!");
					} else {
						alert("測試失敗!");
					}
				},
				error : function() {
					alert("ajax失敗!");
				}
			})
		}
	</script>
</body>
</html>

編輯啓動類

package cn.xxs.ssmcrud;

import ch.qos.logback.core.pattern.Converter;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.text.SimpleDateFormat;
import java.util.Date;

@SpringBootApplication
@MapperScan(basePackages = {"cn.xxs.ssmcrud.mapper"})
public class SsmcrudApplication {

    public static void main(String[] args) {
        SpringApplication.run(SsmcrudApplication.class, args);
    }


}

運行項目啓動類

瀏覽器輸入http://localhost:8080/index

先來測試一下ajax能不能正常訪問

點擊“測試ajax”彈框提醒測試成功

接下來我們測試crud

點擊“用戶列表”

點擊“刪除”

 

 

在數據庫確認

點擊“新增用戶”並輸入添加的內容

點擊“保存”

刷新數據庫

點擊“更新”

點擊"保存"

 

刷新數據庫

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章