Spring Data JPA

准备工作:

  • Maven包管理;(我这里是Spring boot项目,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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.garrett</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</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>mysql</groupId>  
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
            <scope>runtime</scope>
        </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>
			</plugin>
		</plugins>
	</build>

</project>
  • application.properties(mysql数据库需要自己创建,表会自动生成)
# THYMELEAF 
spring.thymeleaf.encoding=UTF-8

spring.thymeleaf.mode=HTML5
# 热部署
spring.thymeleaf.cache=false

# DataSource 
spring.datasource.url=jdbc:mysql://localhost:3306/file?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC 
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
 
# JPA
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto=create-drop
后台代码部分

1、Entity : User(注意注解)

@Entity
public class User {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;
	@Column(nullable = false)
	private String username;   //用户名
	@Column(nullable = false)
	private String name;   //真实姓名
	@Column
	private int age;    //年龄
	@Column
	private String sex;    //性别
	@Column
	private String email;    //邮箱
	@Column
	private String phonenumber;    //手机号
	
	/**
	 * 保护的无参构造方法,防止被直接调用
	 */
	protected User(){
		
	}
	
	public User(String username, String name){
		this.username = username;
		this.name = name;
	}
	
	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 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 getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhonenumber() {
		return phonenumber;
	}

	public void setPhonenumber(String phonenumber) {
		this.phonenumber = phonenumber;
	}

	@Override
	public String toString() {
		return "User[id=%d, username=%s, name=%s, age=%d, sex=%s, email=%s, phonenumber=%s], ";
	}

2、Repository : UserRepository 继承CrudRepository(与数据对接,只不过不在需要写实现而是直接继承CrudRepository)

public interface UserRepository extends CrudRepository<User, Long>{
	
}

3、Controller : UserController(与前端接口对接)

@RestController
@RequestMapping("users")
public class UserController {
	
	@Autowired
	private UserRepository userRepository;
	
	/**
	 * 查询所有用户
	 * @param model
	 * @return
	 */
	@GetMapping()
	public ModelAndView list(Model model){
		model.addAttribute("userList", userRepository.findAll());
		model.addAttribute("title", "用户管理");
		return new ModelAndView("users/list", "userModel", model);
	}
	
	/**
	 * 根据id查看用户
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("{id}")
	public ModelAndView view(@PathVariable("id") Long id, Model model){
		User user = userRepository.findById(id).get();
		model.addAttribute("user", user);
		model.addAttribute("title", "查看用户");
		return new ModelAndView("users/view", "userModel", model);
	}
	
	/**
	 * 获取创建表单页面
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("form")
	public ModelAndView createForm(Model model){
		model.addAttribute("user", new User(null, null));
		model.addAttribute("title", "创建用户");
		return new ModelAndView("users/form", "userModel", model);
	}
	
	/**
	 * 新建用户
	 * @param user
	 * @return
	 */
	@PostMapping
	public ModelAndView saveOrUpdateUser(User user){
		userRepository.save(user);
		return new ModelAndView("redirect:users");
	}
	
	/**
	 * 删除用户
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("delete/{id}")
	public ModelAndView delete(@PathVariable("id") Long id, Model model){
		userRepository.deleteById(id);
		model.addAttribute("userList", userRepository.findAll());
		model.addAttribute("title", "删除用户");
		return new ModelAndView("users/list", "userModel", model);
	}
	
	/**
	 * 修改用户
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("modify/{id}")
	public ModelAndView modify(@PathVariable("id") Long id, Model model){
		User user = userRepository.findById(id).get();
		model.addAttribute("user", user);
		model.addAttribute("title", "修改用户");
		return new ModelAndView("users/form", "userModel", model);
	}

前端代码部分

Spring boot项目中,前端页面放在src/main/resources->templates下我这里新建了一个users目录,用来保存跟user相关的页面

页面使用Thymeleaf模板,在properties里也设置了热部署

页面分为三个:list.html查看所有用户, view.html查看用户信息, form.html注册或修改用户

接口:

Get /users :首页(跳到/users/list)

Get /users/list :用户列表

Get /users/{id} :查看id用户的详细信息(/users/view页面)

Get /users/form : 注册用户

Post /users :提交表单

Get /users/delete/{id} :删除id用户

Get /users/modify/{id} :修改id用户

list.html页面(这里有引入header和footer,你可以直接删去):

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
	xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title th:text="${userModel.title}">welcome</title>
</head>
<body>
	<div th:replace="~{fragments/header :: header}"></div>
	<h3 th:text="${userModel.title}"></h3>

	<div>
		<a href="/users/form.html" th:href="@{~/users/form}">创建用户</a>
	</div>
	<table border="1">
		<thead>
			<tr>
				<td>ID</td>
				<td>UserName</td>
				<td>Name</td>
				<td>Sex</td>
				<td>Age</td>
				<td>Email</td>
				<td>PhoneNumber</td>
			</tr>
		</thead>
		<tbody>
			<tr th:if="${userModel.userList.size()} eq 0">
				<td colspan="7">没有用户信息!</td>
			</tr>
			<tr th:each="user : ${userModel.userList}">
				<td th:text="${user.id}"></td>
				<td ><a th:href="@{'/users/' + ${user.id}}" th:text="${user.username}"></a></td>
				<td th:text="${user.name}"></td>
				<td th:text="${user.sex}"></td>
				<td th:text="${user.age}"></td>
				<td th:text="${user.email}"></td>
				<td th:text="${user.phonenumber}"></td>
			</tr>
		</tbody>
	</table>

	<div th:replace="~{fragments/footer :: footer}"></div>
</body>
</html>

form.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title th:text="${userModel.title}">welcome</title>
</head>
<body>
	<div th:replace="~{fragments/header :: header}"></div>
	<h3 th:text="${userModel.title}"></h3>
	<form action="/users" th:action="@{/users}" method="POST" th:object="${userModel.user}">
		<input type="hidden" name="id" th:value="*{id}">
		用户名:<br>
		<input type="text" name="username" th:value="*{username}"><br>
		真实姓名:<br>
		<input type="text" name="name" th:value="*{name}"><br>
		性别:<br>
		<input type="text" name="sex" th:value="*{sex}"><br>
		年龄:<br>
		<input type="text" name="age" th:value="*{age}"><br>
		邮箱:<br>
		<input type="text" name="email" th:value="*{email}"><br>
		手机号:<br>
		<input type="text" name="phonenumber" th:value="*{phonenumber}"><br>
		<input type="submit" value="提交">
	</form>
	
	<div th:replace="~{fragments/footer :: footer}"></div>
</body>
</html>

view.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title th:text="${userModel.title}">welcome</title>
</head>
<body>
	<div th:replace="~{fragments/header :: header}"></div>
	<h3 th:text="${userModel.title}"></h3>
	<div th:object="${userModel.user}">
		<p><strong>ID : </strong><span th:text="*{id}"></span></p>
		<p><strong>用户名 : </strong><span th:text="*{username}"></span></p>
		<p><strong>真实姓名 : </strong><span th:text="*{name}"></span></p>
		<p><strong>性别 : </strong><span th:text="*{sex}"></span></p>
		<p><strong>年龄 : </strong><span th:text="*{age}"></span></p>
		<p><strong>邮箱 : </strong><span th:text="*{email}"></span></p>
		<p><strong>手机号 : </strong><span th:text="*{phonenumber}"></span></p>
	</div>
	<a th:href="@{'/users/delete/' + ${userModel.user.id}}">删除</a>
	<a th:href="@{'/users/modify/' + ${userModel.user.id}}">修改</a>
	<div th:replace="~{fragments/footer :: footer}"></div>
</body>
</html>

效果图:





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值