maven+spring boot+mybatis实现简单的CURD操作

使用spring boot进行简单的CURD操作的练习(没有添加事务相关的代码),页面使用thymeleaf,这篇文章只是我学习的一个记录,代码很不完整,在这里只是记录一下学习过程。

目录

一、项目的整体结构

二、配置文件

1、pom.xml

2、application.properties

三、数据库SQL

四、实体类

五、controller、service、dao

1、controller

2、service

a、interface

b、class

3、dao

a、interface

b、xml

六、启动类

七、页面

1、add.html

2、modify.html

3、userinfo.html

4、fail.html


一、项目的整体结构

先说一下配置文件

二、配置文件

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>com.llangzh</groupId>
	<artifactId>myspringbootcurd</artifactId>
	<version>1.0.0</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.4.RELEASE</version>
	</parent>

	<properties>
		<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
		<thymeleaf-layout-dialect.version>2.4.1</thymeleaf-layout-dialect.version>
	</properties>

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

		<!-- web启动器 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

		<!-- mybatis启动器 -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.0.1</version>
		</dependency>
	
		<!-- MySQL驱动 -->
		<dependency>
		    <groupId>mysql</groupId>
		    <artifactId>mysql-connector-java</artifactId>
		</dependency>
				
		<!-- druid连接池 -->
		<dependency>
		    <groupId>com.alibaba</groupId>
		    <artifactId>druid</artifactId>
		    <version>1.1.16</version>
		</dependency>
	</dependencies>
</project>

2、application.properties

# 连接池配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/myspringboot?serverTimezone=GMT%2B8&userUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456

#类别名
mybatis.type-aliases-package=com.llangzh.bean

三、数据库SQL

SET FOREIGN_KEY_CHECKS=0;

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `uid` int(5) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) COLLATE utf8_croatian_ci NOT NULL,
  `password` varchar(20) CHARACTER SET utf8 COLLATE utf8_croatian_ci NOT NULL,
  `age` int(3) DEFAULT NULL,
  `address` varchar(40) COLLATE utf8_croatian_ci DEFAULT NULL,
  `email` varchar(40) COLLATE utf8_croatian_ci NOT NULL,
  PRIMARY KEY (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_croatian_ci;

四、实体类

使用hibernate validator注解验证

package com.llangzh.bean;

import javax.validation.constraints.Email;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;

import org.hibernate.validator.constraints.Length;

public class User {
	private Integer uid;
	@NotBlank
	private String username;
	@NotBlank
	private String password;
	@Min(1)
	@Max(150)
	private Integer age;
	@Length(max = 40)
	private String address;
	@Email(regexp = "/^(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w{2,3}){1,3})$/")
	private String email;

	public Integer getUid() {
		return uid;
	}
	public void setUid(Integer uid) {
		this.uid = uid;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
}

五、controller、service、dao

1、controller

package com.llangzh.controller;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.llangzh.bean.User;
import com.llangzh.service.IUserService;

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

	@Autowired
	private IUserService userService;

	@RequestMapping("/addPage")
	public String regesterPage() {
		return "add.html";
	}

	/**
	 * 添加user,添加成功重定向到用户信息页面
	 * @param user
	 * @param model
	 * @param attributes
	 * @return
	 */
	@RequestMapping("/addUser")
	public String addUser(User user, Model model, RedirectAttributes attributes) {
		if (userService.addUser(user)) {
			attributes.addAttribute("uid", user.getUid());
			return "redirect:/userController/findUserByUid";
		}
		return "fail.html";
	}

	/**
	 * 删除用户
	 * @param uid
	 * @return
	 */
	@RequestMapping("/moveUser")
	public String moveUser(Integer uid) {
		if (userService.findUserByUid(uid) != null) {
			userService.moveUserByUid(uid);
			return "redirect:/userController/findAllUser";
		}
		return "fail.html";
	}

	/**
	 * 查找先要修改的用户,查到跳转到修改页面
	 * @param uid
	 * @param model
	 * @return
	 */
	@RequestMapping("/modifyUser")
	public String modifyUser(Integer uid, Model model) {
		User user = userService.findUserByUid(uid);
		if (user != null) {
			model.addAttribute("user", user);
			return "modify.html";
		}
		return "fail.html";
	}
	
	/**
	 * 修改用户,跳转到用户信息页面
	 * @param user
	 * @return
	 */
	@RequestMapping("/modifyUserByUid")
	public String modifyUserByUid(User user) {
		userService.modifyUserByUid(user);
		return "redirect:/userController/findUserByUid?uid=" + user.getUid();
	}

	/**
	 * 查所有用户
	 * @param model
	 * @return
	 */
	@RequestMapping("/findAllUser")
	public String findAllUser(Model model) {
		List<User> users = userService.findAllUser();
		model.addAttribute("users", users);
		return "userinfo.html";
	}

	/**
	 * 通过ID查user,显示到用户信息页面
	 * @param uid
	 * @param model
	 * @return
	 */
	@RequestMapping("/findUserByUid")
	public String findUserByUid(Integer uid, Model model) {
		User user = userService.findUserByUid(uid);
		if (user != null) {
			List<User> users = new ArrayList<User>();
			users.add(user);
			model.addAttribute("users", users);
			return "userinfo.html";
		}
		return "fail.html";
	}
}

2、service

a、interface

package com.llangzh.service;

import java.util.List;

import com.llangzh.bean.User;

public interface IUserService {

	boolean addUser(User user);

	boolean moveUserByUid(Integer uid);

	boolean modifyUserByUid(User user);

	User findUserByUid(Integer uid);

	List<User> findAllUser();

	List<User> findUsersByUserame(String username);
}

b、class

package com.llangzh.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.llangzh.bean.User;
import com.llangzh.dao.IUserDao;
import com.llangzh.service.IUserService;

@Service
public class UserServiceImpl implements IUserService {

	@Autowired
	private IUserDao userDao;
	
	@Override
	public boolean addUser(User user) {
		return userDao.insertUser(user);
	}

	@Override
	public boolean moveUserByUid(Integer uid) {
		return userDao.deleteUserByUid(uid);
	}

	@Override
	public boolean modifyUserByUid(User user) {
		return userDao.updateUserByUid(user);
	}

	@Override
	public User findUserByUid(Integer uid) {
		return userDao.selectUserByUid(uid);
	}

	@Override
	public List<User> findAllUser() {
		return userDao.selectAllUser();
	}

	@Override
	public List<User> findUsersByUserame(String username) {
		return null;
	}
}

3、dao

a、interface

package com.llangzh.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.llangzh.bean.User;

@Repository
public interface IUserDao {

	boolean insertUser(User user);
	
	boolean deleteUserByUid(Integer uid);
	
	boolean updateUserByUid(User user);
	
	User selectUserByUid(Integer uid);
	List<User> selectAllUser();
	List<User> selectUsersByUserame(String username);
}

b、xml

<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.llangzh.dao.IUserDao">

	<insert id="insertUser" useGeneratedKeys="true" keyProperty="uid">
		INSERT INTO `user`(username,password,age,email,address) VALUES (#{username},#{password},#{age},#{email},#{address})
	</insert>
	
	<delete id="deleteUserByUid" flushCache="true">
		DELETE FROM `user` WHERE uid = #{uid}
	</delete>

	<update id="updateUserByUid">
		UPDATE `user` SET
			<if test="username != null and username.trim() != ''">
				username = #{username},
			</if>
			<if test="username != null and username.trim() != ''">
				password = #{password},
			</if>
				age = #{age},
				email = #{email},
				address = #{address}
			<where>
				uid = #{uid}
			</where>
	</update>

	<resultMap type="User" id="userList">
		<id column="uid" property="uid"/>
		<result column="username" property="username"/>
		<result column="password" property="password"/>
		<result column="age" property="age"/>
		<result column="address" property="address"/>
		<result column="eamil" property="eamil"/>
	</resultMap>
	<select id="selectAllUser" resultMap="userList">
		SELECT * FROM `user`
	</select>

	<select id="selectUserByUid" resultType="User">
		SELECT * FROM `user` WHERE uid = #{uid}
	</select>
</mapper>

六、启动类

package com.llangzh;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.llangzh.dao")
public class App {

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

}

七、页面

1、add.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>addUser</title>
</head>
<body>
	<form action="/userController/addUser" method="post">
		用户名:<input type="text" name="username" /><br/>
		密码:<input type="text" name="password" /><br/>
		邮箱:<input type="text" name="email" /><br/>
		年龄:<input type="text" name="age" /><br/>
		地址:<input type="text" name="address" /><br/>
		<input type="submit" value="submit" /><br/>
	</form>
</body>
</html>

2、modify.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>modifyUser</title>
</head>
<body>

	<form action="/userController/modifyUserByUid" method="post">
		<input type="hidden" name="uid" th:field="${user.uid}" /><br/>
		用户名:<input type="text" name="username" th:field="${user.username}" /><br/>	
		密码:<input type="text" name="password" th:field="${user.password}" /><br/>
		年龄:<input type="text" name="age" th:field="${user.age}" /><br/>
		邮箱:<input type="text" name="email" th:field="${user.email}" /><br/>
		地址:<input type="text" name="address" th:field="${user.address}" /><br/>
		<input type="submit" value="modify" />
	</form>
</body>
</html>

3、userinfo.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>userinfo</title>
</head>
<body>

	<table border="1" style="text-align:center; width: 900px;" >
		<tr>
			<th>用户ID</th>		
			<th>用户姓名</th>		
			<th>用户密码</th>		
			<th>用户邮箱</th>		
			<th>用户年龄</th>		
			<th>用户地址</th>	
			<th colspan="2">操作</th>	
		</tr>
		<tr th:each="user : ${users}">
			<td th:text="${user.uid}" />
			<td th:text="${user.username}" />
			<td th:text="${user.password}" />
			<td th:text="${user.email}" />
			<td th:text="${user.age}" />
			<td th:text="${user.address}" />
			<td>
				<a th:href=@{/userController/modifyUser(uid=${user.uid})}>修改用户</a>
			</td>
			<td>
				<a th:href=@{/userController/moveUser(uid=${user.uid})}>删除用户</a>
			</td>
		</tr>
	</table>
</body>
</html>

4、fail.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>fail page</title>
</head>
<body>
	fail page
</body>
</html>

失败操作全部转到这里。。。。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值