spring-boot jpa 使用快速入门
项目结构
pom文件
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.toolz</groupId>
<artifactId>myuser</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>myuser</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork></fork>
</configuration>
</plugin>
</plugins>
</build>
</project>
实体类entity代码
package com.toolz.myuser.entity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import javax.persistence.*;
import java.util.Date;
@Entity
public class Userinfo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(nullable = false, unique = true)
private String userName;
@Column(nullable = false)
private String pwd;
@Column(nullable = false)
private int age;
@Column(nullable = false)
private Date regTime;
public long getId(){
return id;
}
public void setId(long id){
this.id = id;
}
public String getUserName(){
return userName;
}
public void setUserName(String userName){
this.userName = userName;
}
public String getPwd(){
return pwd;
}
public void setPwd(String pwd){
this.pwd = pwd;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
public Date getRegTime(){
return regTime;
}
public void setRegTime(Date regTime){
this.regTime = regTime;
}
@Override
public String toString(){
return ToStringBuilder.reflectionToString(this);
}
}
Application类
package com.toolz.myuser;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class MyuserApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(MyuserApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(MyuserApplication.class, args);
}
}
Controller
package com.toolz.myuser.controller;
import com.toolz.myuser.entity.Userinfo;
import com.toolz.myuser.param.UserParam;
import com.toolz.myuser.repository.UserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Date;
import java.util.List;
@Controller
public class UserController {
@Autowired
private UserRepository userRepository;
@RequestMapping("/")
public String index(){return "redirect:/list";}
@RequestMapping("/list")
public String list(Model model, @RequestParam(value="page", defaultValue = "0") Integer page,
@RequestParam(value = "size", defaultValue = "10") Integer size){
Sort sort = new Sort(Sort.Direction.DESC, "id");
Pageable pageable = new PageRequest(page, size);
Page<Userinfo> userList = userRepository.findList(pageable);
model.addAttribute("users",userList);
return "user/list";
}
@RequestMapping("toAdd")
public String toAdd(){return "user/userAdd";}
@RequestMapping("/add")
public String add(UserParam userParam, BindingResult result, ModelMap model)
{
String errorMsg = "";
if (result.hasErrors())
{
List<ObjectError> list = result.getAllErrors();
for (ObjectError e: list){
errorMsg = errorMsg + e.getCode() + ":" + e.getDefaultMessage();
}
model.addAttribute("errorMsg", errorMsg);
return "user/userAdd";
}
Userinfo u = userRepository.findByUserName(userParam.getUserName());
if(u!=null)
{
model.addAttribute("errorMsg", "用户名已存在");
return "user/userAdd";
}
Userinfo user = new Userinfo();
BeanUtils.copyProperties(userParam, user);
user.setRegTime(new Date());
userRepository.save(user);
return "redirect:/list";
}
@RequestMapping("/delete")
public String del(Long id){
userRepository.deleteById(id);
return "redirect:/list";
}
@RequestMapping("toEdit")
public String edit(Long id){
return "user/userAdd";
}
}
DAO
package com.toolz.myuser.repository;
import com.toolz.myuser.entity.Userinfo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import javax.transaction.Transactional;
import java.util.Optional;
public interface UserRepository extends JpaRepository<Userinfo, Long> {
@Query("select u from Userinfo u")
Page<Userinfo> findList(Pageable pageable);
@Override
Optional<Userinfo> findById(Long id);
// 简单自定义查询
Userinfo findByUserName(String userName);
void deleteById(Long id);
@Modifying
@Transactional
@Query(value ="delete from Userinfo u where u.userName = ?1")
void deleteByUserName(String userName);
}
Param
package com.toolz.myuser.param;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
public class UserParam {
private long id;
@NotEmpty(message = "用户名不能为空")
private String userName;
@NotEmpty(message = "用户名不能为空")
@Length(message = "密码长度不能少于6位")
private String pwd;
@Max(value = 100, message = "年龄不能大于100")
@Min(value = 1, message = "年龄必须大于1")
private int age;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
重写的启动类
package com.toolz.myuser;
import com.toolz.myuser.entity.Userinfo;
import com.toolz.myuser.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.util.Date;
@Profile(value = "dev")
@Component
public class MyStartupRunner implements CommandLineRunner {
@Autowired
private UserRepository userRepository;
private String addUser(Userinfo user){
String name = "zhangsan";
String pwd = "abc";
int age = 18;
Userinfo u = userRepository.findByUserName(name);
if(u!=null)
{
System.out.println("该用户已存在");
userRepository.deleteByUserName(name);
System.out.println("该用户已被清除");
}
user.setUserName(name);
user.setPwd(pwd);
user.setAge(age);
user.setRegTime(new Date());
userRepository.save(user);
return "用户保存成功";
}
public void run(String... strings) throws Exception {
System.out.println("项目启动了!!!!!!!!!!!!!!!!!!!!!!");
System.out.println("开始添加用户");
String res = addUser(new Userinfo());
System.out.println(res);
}
}
配置文件
application.properties
# 自动创建/更新/验证数据库表结构
spring.jpa.properties.hibernate.hbm2ddl.auto = update
# 设置数据库引擎为innodb
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
# 终端输出sql语句
spring.jpa.show-sql=true
# 开发为false
spring.thymeleaf.cache=false
#server.port=8080
spring.profiles.active=dev
application-dev.properties
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password = mysql
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
server.port=8081
list.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
</head>
<body class="container">
<h1>用户列表</h1>
<br/>
<div class="width:80%">
<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>用户名</th>
<th>密码</th>
<th>年龄</th>
<th>注册时间</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr th:each ="u:${users}">
<td scope="row" th:text="${u.id}">1111</td>
<td th:text="${u.userName}">Wayne</td>
<td th:text="${u.pwd}">abcabcabc</td>
<td th:text="${u.age}">120</td>
<td th:text="${u.regTime}">2018/12/27</td>
<td><a th:href="@{/toEdit(id=${u.id})}">编辑</a></td>
<td><a th:href="@{/delete(id=${u.id})}" onclick="return confirm('确认删除该用户吗?')">删除</a></td>
</tr>
</tbody>
</table>
</div>
<div class="form-group">
<div class="col-sm-2 control-label">
<a href="/toAdd" class="btn btn-info">添加</a>
</div>
</div>
</body>
</html>
userAdd.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>添加用户</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
</head>
<body class="container">
<h1>添加用户</h1>
<br/>
<form th:action="@{/add}" method="post" class="form-horizontal">
<div class="form-group">
<label for="userName" class="col-sm-2 control-label">用户名</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="userName" id="userName" placeholder="用户名">
</div>
</div>
<div class="form-group">
<label for="userName" class="col-sm-2 control-label">密码</label>
<div class="col-sm-10">
<input type="password" class="form-control" name="pwd" id="pwd" placeholder="密码">
</div>
</div>
<div class="form-group">
<label for="userName" class="col-sm-2 control-label">年龄</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="age" id="age" placeholder="年龄">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"></label>
<div class="col-sm-10">
<div th:if="${errorMsg!=null}" class="alert alert-danger" role="alert" th:text="${errorMsg}">
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" value="添加" class="btn btn-info">
<input type="reset" value="重置" class="btn btn-info">
<a th:href="@{/list}">后退</a>
</div>
</div>
</form>
</body>
</html>