笔记65 Spring Boot快速入门(五)
SpringBoot+JPA
一、什么是JPA?
JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。真正干活的可能是Hibernate,TopLink等等实现了JPA规范的不同厂商,默认是Hibernate。
二、在springboot中使用JPA对数据库进行抽插
(一)目录结构

(二)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.example</groupId>
<artifactId>springboot-jpa-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>springboot-jpa-demo</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.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-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
1.数据库准备:创建表,插入数据等(略)
给出application.properties
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/sh?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update server.port=8080
server.context-path=/Test·
2.IDEA新建项目(列出比较重要的步骤)


3.新建pojo——Category
package com.example.springbootjpademo.pojo; import javax.persistence.*; @Entity
@Table(name = "category")
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id; @Column(name = "name")
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
4.创建DAO
创建dao接口CategoryDAO,继承了JpaRepository,并且提供泛型<Category,Integer> 表示这个是针对Category类的DAO,Integer表示主键是Integer类型。
JpaRepository 这个父接口,就提供了CRUD, 分页等等一系列的查询了,直接拿来用,都不需要二次开发的了。
package com.example.springbootjpademo.dao; import com.example.springbootjpademo.pojo.Category;
import org.springframework.data.jpa.repository.JpaRepository; public interface CategoryDAO extends JpaRepository<Category,Integer> {
}
5.创建Controller
自动加载CategoryDAO,然后调用findAll()查询所有条目。
package com.example.springbootjpademo.controller; import com.example.springbootjpademo.dao.CategoryDAO;
import com.example.springbootjpademo.pojo.Category;
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 java.util.List;
@Controller
public class CategoryController {
@Autowired
CategoryDAO categoryDAO; @RequestMapping("/listCategory")
public String ListCategory(Model model) throws Exception{
List<Category> categoryList=categoryDAO.findAll();
model.addAttribute("categories",categoryList);
return "listCategory";
}
}
6.创建view(使用Thymeleaf)
listCategory.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Title</title>
</head>
<body>
<div class="showing">
<h2>springboot+jpa</h2> <table>
<thead>
<tr>
<th>id</th>
<th>name</th>
</tr>
</thead>
<tbody>
<tr th:each="c: ${categories}">
<td align="center" th:text="${c.id}"></td>
<td align="center" th:text="${c.name}"></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
7.测试

三、总结(目前遇到的问题,可能有出入)
1.注意springboot自动扫描和装配的规则。
SpringBoot项目的Bean装配默认规则是根据Application类所在的包位置从上往下扫描!
“Application类”是指SpringBoot项目入口类。这个类的位置很关键:
如果Application类所在的包为:com.boot.app,则只会扫描com.boot.app包及其所有子包,如果service或dao所在包不在com.boot.app及其子包下,则不会被扫描!
即, 把Application类放到dao、service所在包的上级,com.boot.Application
2.jpa与2.0.3版本的springboot之间存在冲突,会导致项目出现问题。
3.JpaRepository 继承PagingAndSortingRepository,实现一组JPA规范相关的方法。
<1>什么是Repository
Repository(资源库):通过用来访问领域对象的一个类似集合的接口,在领域与数据映射层之间进行协调。这个叫法就类似于我们通常所说的DAO,在这里,我们就按照这一习惯把数据访问层叫Repository
Spring Data给我们提供几个Repository,基础的Repository提供了最基本的数据访问功能,其几个子接口则扩展了一些功能。它们的继承关系如下:
Repository: 仅仅是一个标识,表明任何继承它的均为仓库接口类,方便Spring自动扫描识别
CrudRepository: 继承Repository,实现了一组CRUD相关的方法

PagingAndSortingRepository: 继承CrudRepository,实现了一组分页排序相关的方法

JpaRepository: 继承PagingAndSortingRepository,实现一组JPA规范相关的方法

JpaSpecificationExecutor: 比较特殊,不属于Repository体系,实现一组JPA Criteria查询相关的方法
我们自己定义的XxxxRepository需要继承JpaRepository,这样我们的XxxxRepository接口就具备了通用的数据访问控制层的能力。
<2>CrudRepository接口
T save(T entity);//保存单个实体
Iterable<T> save(Iterable<? extends T> entities);//保存集合
T findOne(ID id);//根据id查找实体
boolean exists(ID id);//根据id判断实体是否存在
Iterable<T> findAll();//查询所有实体,不用或慎用!
long count();//查询实体数量
void delete(ID id);//根据Id删除实体
void delete(T entity);//删除一个实体
void delete(Iterable<? extends T> entities);//删除一个实体的集合
void deleteAll();//删除所有实体,不用或慎用!
<3>PagingAndSortingRepository接口
这个接口提供了分页与排序功能
Iterable<T> findAll(Sort sort);//排序
Page<T> findAll(Pageable pageable);//分页查询(含排序功能)
<4>JpaRepository接口
这个接口提供了JPA的相关功能
List<T> findAll();//查找所有实体
List<T> findAll(Sort sort);//排序 查找所有实体
List<T> save(Iterable<? extends T> entities);//保存集合
void flush();//执行缓存与数据库同步
T saveAndFlush(T entity);//强制执行持久化
void deleteInBatch(Iterable<T> entities);//删除一个实体集合
四、使用JPA进行CRUD和分页
1.在CategoryController中添加映射:增、删、改、查。
@RequestMapping("/listCategories")
public String ListCategories(Model model,
@RequestParam(value = "start",defaultValue = "0")int start,
@RequestParam(value = "size",defaultValue = "5") int size
) throws Exception{
start=start<0?0:start;
Sort sort=new Sort(Sort.Direction.DESC,"id");
Pageable pageable=new PageRequest(start,size,sort);
Page<Category> page=categoryDAO.findAll(pageable);
model.addAttribute("page",page);
return "listCategories";
}
//JPA 新增和修改用的都是save. 它根据实体类的id是否为0来判断是进行增加还是修改
@RequestMapping("/addCategory")
public String addCategory(Category category) throws Exception{
categoryDAO.save(category);
return "redirect:listCategories";
}
@RequestMapping("/deleteCategory")
public String deleteCategory(Category category)throws Exception{
categoryDAO.delete(category);
return "redirect:listCategories";
}
@RequestMapping("/updateCategory")
public String updateCategory(Category category)throws Exception{
categoryDAO.save(category);
return "redirect:listCategories";
}
@RequestMapping("/editCategory")
public String editCategory(int id,Model model)throws Exception{
Category category=categoryDAO.getOne(id);
model.addAttribute("category",category);
return "editCategory";
}
知识点:
<1>Page是Spring Data提供的一个接口,该接口表示一部分数据的集合以及其相关的下一部分数据、数据总数等相关信息,通过该接口,我们可以得到数据的总体信息(数据总数、总页数...)以及当前数据的信息(当前数据的集合、当前页数等)。
public interface Page<T> extends Iterable<T> {
int getNumber(); //当前第几页 返回当前页的数目。总是非负的
int getSize(); //返回当前页面的大小。
int getTotalPages(); //返回分页总数。
int getNumberOfElements(); //返回当前页上的元素数。
long getTotalElements(); //返回元素总数。
boolean hasPreviousPage(); //返回如果有上一页。
boolean isFirstPage(); //返回当前页是否为第一页。
boolean hasNextPage(); //返回如果有下一页。
boolean isLastPage(); //返回当前页是否为最后一页。
Iterator<T> iterator();
List<T> getContent(); //将所有数据返回为List
boolean hasContent(); //返回数据是否有内容。
Sort getSort(); //返回页的排序参数。
}
<2>Pageable 是Spring Data库中定义的一个接口,该接口是所有分页相关信息的一个抽象,通过该接口,我们可以得到和分页相关所有信息(例如pageNumber、pageSize等),这样,Jpa就能够通过pageable参数来得到一个带分页信息的Sql语句。
/**
* 分页信息抽象接口
*
* @author Oliver Gierke
*/
public interface Pageable { /**
* 返回要返回的页面.
*
* @return the page to be returned.
*/
int getPageNumber(); /**
* 返回要返回的项目的数量。
*
* @return the number of items of that page
*/
int getPageSize(); /**
* 根据底层页面和页面大小返回偏移量。
*
* @return the offset to be taken
*/
int getOffset(); /**
* 返回排序参数。
*
* @return
*/
Sort getSort();
}
2.数据展示页listCategories.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Title</title>
</head>
<body>
<div class="showing">
<h2>springboot+jpa</h2>
<div style="width:500px;margin:20px auto;text-align: center">
<table align="center" border="1" cellspacing="0">
<thead>
<tr>
<th>id</th>
<th>name</th>
<td>编辑</td>
<td>删除</td>
</tr>
</thead>
<tbody>
<tr th:each="c: ${page}">
<td align="center" th:text="${c.id}"></td>
<td align="center" th:text="${c.name}"></td>
<td align="center" ><a th:href="@{/editCategory(id=${c.id})}">编辑</a></td>
<td align="center" ><a th:href="@{/deleteCategory(id=${c.id})}">删除</a></td>
</tr>
</tbody>
</table>
<br />
<div>
<a th:href="@{/listCategories(start=0)}">[首 页]</a>
<a th:href="@{/listCategories(start=${page.number -1})}">[上一页]</a>
<a th:href="@{/listCategories(start=${page.number +1})}">[下一页]</a>
<a th:href="@{/listCategories(start=${page.totalPages -1})}">[末 页]</a>
</div>
<form action="/addCategory" method="post">
name:<input name="name"/><br/>
<button type="submit">提交</button>
</form>
</div>
</div>
</body>
</html>
3.修改页面editCategory.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Title</title>
</head>
<body>
<div class="showing">
<h2>springboot+jpa</h2> <div style="margin:0px auto; width:500px"> <form action="/updateCategory" method="post"> name: <input name="name" th:value="${category.name}" /> <br/> <input name="id" type="hidden" th:value="${category.id}" />
<button type="submit">提交</button> </form>
</div>
</div>
</body>
</html>
4.测试

五、代码
https://github.com/lyj8330328/springboot-jpa-demo
笔记65 Spring Boot快速入门(五)的更多相关文章
- 笔记61 Spring Boot快速入门(一)
IDEA+Spring Boot快速搭建 一.IDEA创建项目 略 项目创建成功后在resources包下,属性文件application.properties中,把数据库连接属性加上,同时可以设置服 ...
- 笔记63 Spring Boot快速入门(三)
SpringBoot中使用JSP Springboot的默认视图支持是Thymeleaf,但是Thymeleaf还没开始学,熟悉的还是jsp,所以要让Springboot支持 jsp. 一.在pom. ...
- 笔记70 Spring Boot快速入门(八)(重要)
上传文件 一.方式一 1.上传页面 upLoadPage.html <!DOCTYPE html> <html lang="en"> <head> ...
- 笔记64 Spring Boot快速入门(四)
SpringBoot中错误处理.端口设置和上下文路径以及配置切换 一.错误处理 假设在访问首页的时候会出现一些错误,然后将这些错误当作异常抛出,反馈给用户. 1.修改IndexController.j ...
- 笔记62 Spring Boot快速入门(二)
SpringBoot部署 一.jar方式 1.首先安装maven. <1>下载最新的maven版本:https://maven.apache.org/download.cgi <2& ...
- 笔记67 Spring Boot快速入门(七)
SpringBoot+RESTful+JSON 一.RESTful架构 REST全称是Representational State Transfer,中文意思是表述(编者注:通常译为表征)性状态转移. ...
- 笔记66 Spring Boot快速入门(六)
SpringBoot中使用Mybatis 一.注解方式 1.创建映射文件CategoryMapper.java 使用注解@Mapper 表示这是一个Mybatis Mapper接口.使用@Select ...
- Spring Boot 快速入门
Spring Boot 快速入门 http://blog.csdn.net/xiaoyu411502/article/details/47864969 今天给大家介绍一下Spring Boot MVC ...
- Spring Boot快速入门(二):http请求
原文地址:https://lierabbit.cn/articles/4 一.准备 postman:一个接口测试工具 创建一个新工程 选择web 不会的请看Spring Boot快速入门(一):Hel ...
随机推荐
- 入门phantomjs
前言 phantomjs是一个无界面浏览器,用来操作web页面的一个工具,比如登录,提交表单等等. 语法框 //创建一个浏览器对象 var page = require('webpage').crea ...
- PHP实现笛卡尔积算法
概念 在数学中,两个集合X和Y的笛卡儿积(Cartesian product),又称直积,表示为 X × Y.设A.B是任意两个集合,在集合A中任意取一个元素x,在集合B中任意取一个元素y,组成一个有 ...
- windows10 配置SSH连接Github、配置SSH Key
由于你的本地Git仓库和GitHub仓库之间的传输是通过SSH加密的,所以,需要设置SSH key. 第1步:创建SSH Key.在用户主目录下[我的电脑是C:\Users\ad],看看有没有.ssh ...
- 理解Python中的继承规则和继承顺序
先来看一段代码: class First(object): def __init__(self): print ("first") class Second(object): de ...
- 在 IntelliJ IDEA 中这样使用 Git,效率提升2倍以上
1.Git简介 Git是目前流行的分布式版本管理系统.它拥有两套版本库,本地库和远程库,在不进行合并和删除之类的操作时这两套版本库互不影响.也因此其近乎所有的操作都是本地执行,所以在断网的情况下任然可 ...
- java版扫雷
package com.titian.bean; import java.awt.CardLayout; import java.awt.Point; public class Grid { char ...
- 自己总结的CSS3中transform变换、transition过渡、animation动画的基本用法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&quo ...
- 前端每日实战:77# 视频演示如何用纯 CSS 创作旗帜飘扬的动画
效果预览 按下右侧的"点击预览"按钮可以在当前页面预览,点击链接可以全屏预览. https://codepen.io/comehope/pen/qydvBm 可交互视频 此视频是可 ...
- linux(centos6) 常用操作
目录 一.开机关机 1.Linux centos重启命令: 2.Linux centos关机命令: 二.图形界面与命令界面的切换 1.修改/etc/inittab文件,文件中,最后一行id:5:ini ...
- 没有找到MSVCR110.dll,因此这个应用程序未能启动.重新安装应用程序可能会修复此问题
问题: 在win7下用vs2012编译了一个exe放到xp上运行,弹出错误框"没有找到MSVCR110.dll,因此这个应用程序未能启动.重新安装应用程序可能会修复此问题" 解决办 ...