数据持久化Spring Data JPA
项目集成了spring boot+spring data JPA+thymeleaf
前台代码地址:
https://blog.51cto.com/13501268/2319622
1.JPA理解:是用于管理Java EE和Java SE环境中的持久化,1.以及对象/关系映射的Java API
2.核心概念:
(1)实体:实体表示关系数据库中的表
(2)每个实体实例对应于该表中的行
(3)类必须用javas.persistence.Entity注解
(4)类必须有一个public或protected的的无参构造函数
(5)实体实例被当做值以分离对象方式进行传递(例如通过会话bean的远程业务接口),则该类必须实现Serializable接口
(6)唯一的对象标识符:简单主键(javax.persistence.Id),复合主键(javax.persistence.Embeddedld和javax.persistence.IdClass)
3.关系:
(1)一对一:@OneToOne
(2)一对多:@OneToMany
(3)多对一:@ManyToOne
(4)多对多:@ManyToMany
4.EntityManager接口:
(1)定义用于与持久化上下文进行交互的方法
(2)创建和删除持久化实例,通过实体的主键查找实体
5.Spring Data JPA:
(1)是更大的Spring Data家族的一部分
(2)对基于JPA的数据访问层的增强支持
(3)更容易构建基于使用Spring数据访问技术栈的应用
6.Spring Data JPA常用接口:
(1)CurdRepository:
(2)PagingAndSortingRepository:
7.Spring Data JPA自定义接口:
(1)根据方法名查询,方法名命名一定要遵循规则
8.Spring Data JPA,Hibernate与Spring Boot的集成
(1)环境配置:MySql数据库,Hibernate框架,以及Mysql连接驱动
(2)修改pom.xml文件,添加Spring Data JPA以及数据库连接驱动的依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://×××w.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.dhtt.spring.boot.blog</groupId>
<artifactId>spring.data.action</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring.data.action</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.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-data-jpa</artifactId>
</dependency>
<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-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 内存数据库h3 -->
<!--
<dependency>
<groupId>com.h3database</groupId>
<artifactId>h3</artifactId>
</dependency>
-->
<!-- Mysql数据库连接驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!-- hibernate持久层框架引入 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.7.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
(3)启动项目进行测试,我们发现项目正常启动,说明我们的环境已经配置好了
9.集成后台编码:
(1)User实体:加@Entity注解,唯一标识@Id注解,制定主键生成策略,无参构造改造为protected,防止直接使用,加toString方法,实现Serializable接口;
package com.dhtt.spring.boot.blog.spring.data.action.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* user实体
*
* @author QT
*/
@Entity
public class User implements Serializable {
private static final long serialVersionUID = 516988700978313579L;
@Id // 主键
@GeneratedValue(strategy = GenerationType.IDENTITY) // 自增策略
private Long id; // 用户的唯一标识
private String name; // 用户名
private String email; // 用户邮箱
protected User() { // 防止直接使用
super();
}
public User(Long id, String name, String email) {
super();
this.id = id;
this.name = name;
this.email = email;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", email=" + email + "]";
}
}
(2)资源库:写userRepository接口继承JpaRepository接口
package com.dhtt.spring.boot.blog.spring.data.action.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.dhtt.spring.boot.blog.spring.data.action.entity.User;
/**
* User Repository接口
* @author QT
*
*/
@Repository
public interface UserRepository extends JpaRepository<User, Long>{
}
(3)编写userController类,用于与前台进行交互
package com.dhtt.spring.boot.blog.spring.data.action.web.user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.dhtt.spring.boot.blog.spring.data.action.entity.User;
import com.dhtt.spring.boot.blog.spring.data.action.repository.UserRepository;
@Controller
@RequestMapping("/users")
public class userController {
@Autowired
private UserRepository userRepository;
/**
* 查询所有用户
*
* @param model
* @return
*/
@GetMapping
public ModelAndView getList(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.getOne(id);
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, null));
model.addAttribute("title", "创建用户");
return new ModelAndView("users/form", "userModel", model);
}
/**
* 新增或修改用户
*
* @param user
* @return
*/
@PostMapping
public ModelAndView saveOrUpdateUser(User user) {
user = userRepository.save(user);
return new ModelAndView("redirect:/users", "userModel", user);
}
/**
* 获取删除用户
*
* @param id
* @return
*/
@GetMapping("/delete/{id}")
public ModelAndView deleteUser(@PathVariable("id") Long id) {
userRepository.deleteById(id);;
return new ModelAndView("redirect:/users"); // 重定向到list页面
}
/**
* 获取修改用户界面
*
* @param id
* @param model
* @return
*/
@GetMapping("/modify/{id}")
public ModelAndView modify(@PathVariable("id") Long id, Model model) {
User user = userRepository.getOne(id);
model.addAttribute("user", user);
model.addAttribute("title", "修改用户");
return new ModelAndView("users/form", "userModel", model);
}
}
前台与上一个项目一样,直接粘贴复制就好
前台代码项目地址:
https://blog.51cto.com/13501268/2319622
接下里,启动项目,项目运行正常说明集成成功,下一步我们就将数据进行持久化到数据库中
10.将数据持久化到数据库中
(1)进行数据库配置,配置文件如下
#thymeleaf配置
spring.thymeleaf.encoding=UTF-8
#热部署静态文件,不需要缓存,实时观察文件修改效果
spring.thymeleaf.cache=false
#使用html5标准
spring.thymeleaf.mode=HTML5
spring.thymeleaf.suffix=.html
spring.resources.chain.strategy.content.enabled=true
#数据库连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/blog_test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false
spring.datasource.username=root
spring.datasource.password=qitao1996
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#jpa配置
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
(2)接下来启动数据库,建立数据库
接下来我们启动项目进行操作,我们会发现数据库表成功创建,也可以操作表中数据
至此,Spring boot+Spring Data Jpa+mevan+Thymeleaf集成成功完成
原创文章,作者:3628473679,如若转载,请注明出处:https://blog.ytso.com/tech/opensource/193215.html