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快速入门(五)的更多相关文章

  1. 笔记61 Spring Boot快速入门(一)

    IDEA+Spring Boot快速搭建 一.IDEA创建项目 略 项目创建成功后在resources包下,属性文件application.properties中,把数据库连接属性加上,同时可以设置服 ...

  2. 笔记63 Spring Boot快速入门(三)

    SpringBoot中使用JSP Springboot的默认视图支持是Thymeleaf,但是Thymeleaf还没开始学,熟悉的还是jsp,所以要让Springboot支持 jsp. 一.在pom. ...

  3. 笔记70 Spring Boot快速入门(八)(重要)

    上传文件 一.方式一 1.上传页面 upLoadPage.html <!DOCTYPE html> <html lang="en"> <head> ...

  4. 笔记64 Spring Boot快速入门(四)

    SpringBoot中错误处理.端口设置和上下文路径以及配置切换 一.错误处理 假设在访问首页的时候会出现一些错误,然后将这些错误当作异常抛出,反馈给用户. 1.修改IndexController.j ...

  5. 笔记62 Spring Boot快速入门(二)

    SpringBoot部署 一.jar方式 1.首先安装maven. <1>下载最新的maven版本:https://maven.apache.org/download.cgi <2& ...

  6. 笔记67 Spring Boot快速入门(七)

    SpringBoot+RESTful+JSON 一.RESTful架构 REST全称是Representational State Transfer,中文意思是表述(编者注:通常译为表征)性状态转移. ...

  7. 笔记66 Spring Boot快速入门(六)

    SpringBoot中使用Mybatis 一.注解方式 1.创建映射文件CategoryMapper.java 使用注解@Mapper 表示这是一个Mybatis Mapper接口.使用@Select ...

  8. Spring Boot 快速入门

    Spring Boot 快速入门 http://blog.csdn.net/xiaoyu411502/article/details/47864969 今天给大家介绍一下Spring Boot MVC ...

  9. Spring Boot快速入门(二):http请求

    原文地址:https://lierabbit.cn/articles/4 一.准备 postman:一个接口测试工具 创建一个新工程 选择web 不会的请看Spring Boot快速入门(一):Hel ...

随机推荐

  1. webpack从入门到精通(一)

    1.webpack的使用背景: 目前国内前端开发都是基于模块化的 2.webpack的作用有哪些: 3.webpack四大核心理念: entry,output,loaders,plugins 4.使用 ...

  2. rabbitmq的管理软件以及PHP7安装rabbitmq的

    rabbitmq-server管理软件的安装 1.mac下载rabbitmq-server brew install rabbitmq 2.启动服务rabbitmq-server rabbitmq-s ...

  3. MySQL-常用引擎

    来自:https://www.cnblogs.com/xujishou/p/6343431.html :https://www.cnblogs.com/laowenBlog/p/8405614.htm ...

  4. iOS项目开发中的知识点与问题收集整理②

    1.点击UIButton 无法产生触摸事件    如果在UIImageView中添加了一个按钮,你会发现在默认情况下这个按钮是无法被点击的,需要设置UIImageView的userInteractio ...

  5. activemq消息中间件的依赖

    <dependencies> <dependency> <groupId>org.apache.activemq</groupId> <artif ...

  6. RzPageControl(pagecontrol)

    实现多标签的动态添加,切换,关闭 使用RzPageControl来实现多标签页使用菜单来打开标签页,通过标签页的caption来判断将标签页是否已经被打开过了.1.创建标签页,并判断是否是已经打开过的 ...

  7. CEF的备忘笔记

    CEF: Chromium Embeded Framewrok;  (Chromium嵌入式框架)可以在PC(Linux,MacOS,Windows)上把Chromium的内核嵌入到应用程序的框架: ...

  8. 一次且仅一次(once and only once,简称OAOO)

    一次且仅一次(once and only once,简称OAOO)又称为 Don't repeat yourself(不要重复你自己,简称DRY)或一个规则,实现一次(one rule, one pl ...

  9. 搭建Linux C语言开发环境

    1.操作系统 Windows操作系统:windows 7 and windows 10 2.开发工具和编译工具 开发工具:notpad++ 和 vim 编译工具:Cygwin64 Terminal 3 ...

  10. spring 数据库字段映射

    当有复杂名称字段时: 在repository中写代码字段名 List<Grid> findByLocIsWithin(GeoJsonPolygon boundary); 可以添加field ...