SpringBoot study notes (four, JPA)

Front: Jsp view

Springboot default view is supported Thymeleaf, not learned, jsp Jiaoshu with them, first with it about the transition.
1, add support for Jsp in the pom.xml:

<!-- servlet依赖. -->
        <dependency>
              <groupId>javax.servlet</groupId>
              <artifactId>javax.servlet-api</artifactId>
               
        </dependency>
              <dependency>
                     <groupId>javax.servlet</groupId>
                     <artifactId>jstl</artifactId>
              </dependency>
        <!-- tomcat的支持.,用于编译jsp-->
        <dependency>
               <groupId>org.apache.tomcat.embed</groupId>
               <artifactId>tomcat-embed-jasper</artifactId>
                
        </dependency> 

application.properties configuration:

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

This is the front and suffix jsp files, the new WEB-INF folder in the webapp, in the WEB-INF folder New jsp, jsp file is placed in this configuration on jsp is complete, you can also write Controller jsp and to test whether the configuration.

First, the integration of JPA

I had not seen this stuff, first look at JPA:
JPA stands for Java Persistence API.JPA through JDK 5.0 annotations or XML description of the object - mapping between relational tables, solid objects and run persistence to the database.
One of the goals is to develop JPA API that can be implemented by many vendors, and developers can code to implement the API, instead of using proprietary vendor-specific API.
JPA Provider is required to achieve its function, Hibernate JPA Provider is in a very strong, it should be said that no one can match his. In terms of functionality, JPA is a subset of Hibernate features.

1, add the appropriate add dependency in pom.xml dependency:
Add spring-boot-starter-jdbc dependency:

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa
			</artifactId>
</dependency>

Add mysql connection and connection pool class:

<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
</dependency> 

Complete pom.xml

<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>edu.hpu</groupId>
  <artifactId>SpringBoot</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringBoot</name>
  <!-- Spring Boot 启动父依赖 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>
    <dependencies>
        <!-- Spring Boot web依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- spring test -->
        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-test</artifactId>
           <scope>test</scope>
        </dependency>
        <!-- Junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- 添加servlet依赖 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        
        <!--添加 jstl依赖 -->
        <dependency>
           <groupId>javax.servlet</groupId>
           <artifactId>jstl</artifactId>
        </dependency>
        
        <!-- 用于编译jsp -->
        <dependency>
           <groupId>org.apache.tomcat.embed</groupId>
           <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        
        <!-- 热部署依赖 -->
        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional> <!-- 这个需要为 true 热部署才有效 -->
        </dependency>
        
        <!-- 添加对mysql的支持 -->
        <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>5.1.21</version>
        </dependency>
        
        <!-- 添加对jpa的支持 -->
        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    </dependencies>
    
    <properties>
      <java.version>1.8</java.version>
    </properties>
    
    <build>
       <plugins>
           <plugin>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-maven-plugin</artifactId>
           </plugin>
       </plugins>
    </build>
</project>

2, data source
JPA is doing, is to carry out database persistence, we have to have the data. Here is a database with mysql.
Create the database:

create database springbootjpa;

Create a table:

use springbootjpa;
CREATE TABLE category_ (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(30),
  PRIMARY KEY (id)
) DEFAULT CHARSET=UTF8;

Adding data:
this looked just add it.

3, data source configuration:
configure the application in the data source,

spring.datasource.url=jdbc:mysql://localhost:3306/springbootjpa?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=xing0515
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update

Complete application.properties:

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
spring.datasource.url=jdbc:mysql://localhost:3306/springbootjpa?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=xing0515
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update

4, create entity classes
create a new package edu.hpu.springboot.pojo, the new entity classes in Category packet, as follows:

package edu.hpu.springboot.pojo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

//对应category_的实体类
@Entity                            //表示这是个实体类
@Table(name="category_")       //表示对应的表
public class Category {
   @Id                               //表示主键
   @GeneratedValue(strategy = GenerationType.IDENTITY)   //表明自增长方式
   @Column(name="id")                           //表示对应的字段
   private int id;
   
   @Column
   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;
}
   
   @Override
	public String toString() {
		return "Category [id=" + id + ", name=" + name + "]";
	}
}

About the corresponding notes:

annotation Explanation
@Entity Declare the class as an entity or table.
@Table Statement table name.
@Basic Designated non-binding clear the fields.
@Embedded A class or attribute and its value is an instance of the entity class embedded.
@Id Specified class attribute for identifying (primary key of a table).
@GeneratedValue Specify how to identify property may be initialized, such as automatic, manual, or a value obtained from the Sequence Listing.
@Transient Specified property, it is not lasting, namely: the value is never stored in the database.
@Column Properties specify persistent attribute column.
@SequenceGenerator Specify the value specified in the @GeneratedValue annotation attributes. It creates a sequence.
@TableGenerator Specified in the annotation @GeneratedValue specified property value generator. It creates value generated table.
@AccessType This type of comment is used to set the type of access. If you set
@AccessType(FIELD ) It can directly access the variables and does not require getter and setter, but it must be public. If @AccessType (PROPERTY), access Entity through getter and setter methods variables.
@JoinColumn Organization or entity designated a collection of entities. It is used in many-to-many and association.
@UniqueConstraint And a unique constraint specified field for the primary or secondary table.
@ColumnResult SQL query reference column names in the select clause.
@ManyToMany It defines the relationship between the many-to-many connection table.
@ManyToOne Many-defined relation between the connection table.
@OneToMany Defines a one to many relationship exists between the connection table.
@OneToOne It defines a one to one relationship between the connection table.
@NamedQueries Specifies a list of named queries.
@NamedQuery Specify a query using a static name

5, CategoryDao
New Package edu.hpu.springoot.dao, New Interface package at CategoryDao, inherited inherited JpaRepository, and provide the generic <Category, Integer> represents this is for the Category class of the DAO, Integer Integer indicates the type of the primary key is.

package edu.hpu.springboot.dao;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import edu.hpu.springboot.pojo.*;
/*继承了JpaRepository,并且提供泛型<Category,Integer> 
 * 表示这个是针对Category类的DAO,Integer表示主键是Integer类型
 * JpaRepository 这个父接口,就提供了CRUD, 分页等等一系列的查询了,直接拿来用
 */
public interface CategoryDao extends JpaRepository<Category, Integer>{
     public List<Category> findByName(String name);
     public List<Category> findByNameLikeAndIdGreaterThanOrderByNameAsc(String name, int id);
}

Some pre-generation method provided JpaRepository:
Here Insert Picture Descriptioncan also customize some queries, look at the back.

6, CategoryController
this omits Service, usually can not be omitted, the new package edu ... hpu.springboot.web, create a class CategoryController

package edu.hpu.springboot.web;
import java.util.List;
 
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 com.how2java.springboot.dao.CategoryDAO;
import com.how2java.springboot.pojo.Category;
  
@Controller
public class CategoryController {
    @Autowired CategoryDAO categoryDAO;
     
    @RequestMapping("/listCategory")
    public String listCategory(Model m) throws Exception {
        List<Category> cs=categoryDAO.findAll();
         
        m.addAttribute("cs", cs);
         
        return "listCategory";
    }
     
}

7、listCategory.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
   
<table align='center' border='1' cellspacing='0'>
    <tr>
        <td>id</td>
        <td>name</td>
    </tr>
    <c:forEach items="${cs}" var="c" varStatus="st">
        <tr>
            <td>${c.id}</td>
            <td>${c.name}</td>
                
        </tr>
    </c:forEach>
</table>

8. Start Application, visit our Web site http://127.0.0.1:8080/listCategory
Here Insert Picture Description
official document also looked at, not quite that hard, time can take a closer look, enhance your own ability to read English documents. Accessing Data with JPA

Two, CRUD + page

1, modify CategoryController, add, delete, access, modify the mapping

package edu.hpu.springboot.web;

import java.util.List;

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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import edu.hpu.springboot.dao.CategoryDao;
import edu.hpu.springboot.pojo.Category;

@Controller
public class CategoryController {
   @Autowired
   CategoryDao categoryDao;
   
   @RequestMapping("/addCategory")
   public String addCategory(Category c) throws Exception{
	   categoryDao.save(c);
	   return "redirect:listCategory";
   }
   
   @RequestMapping("/deleteCategory")
   public String deleteCategory(Category c) throws Exception{
	   categoryDao.delete(c);
	   return "redirect:listCategory";
   }
   
   @RequestMapping("/editCategory")
   public String editCategory(int id,Model m) throws Exception{
	   Category c=categoryDao.findOne(id);
	   m.addAttribute("c", c);   
	   return "editCategory";
   }
   
   @RequestMapping("/updateCategory")
   public String updateCategory(Category c) throws Exception{
	   categoryDao.save(c);
	  return "redirect:listCategory";
   }
   @RequestMapping("/listCategory")
    public String listCategory(Model m,@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);
	   System.out.println(page.getNumber());
       System.out.println(page.getNumberOfElements());
       System.out.println(page.getSize());
       System.out.println(page.getTotalElements());
       System.out.println(page.getTotalPages());
       m.addAttribute("page", page);
	   return "listCategory";
   }
}

Query mapping also made corresponding changes:
(1) accept the current parameters in the first few pages start, and how many pieces of data per page size. The default values are 0 and 5.

(Model m,@RequestParam(value = "start", defaultValue = "0") int start,@RequestParam(value = "size", defaultValue = "5") int size)

(2), if the start is negative, then changed to 0. This is going to happen in the current home page, and click on the Previous time

start = start<0?0:start;

(3) set down the sort

Sort sort = new Sort(Sort.Direction.DESC, "id");

(4), creates a page object based start, size and sort

Pageable pageable = new PageRequest(start, size, sort);

(5), CategoryDAO obtain the result based on this tab page object.

Page<Category> page =categoryDAO.findAll(pageable);

在这个page对象里,不仅包含了分页信息,还包含了数据信息,即有哪些分类数据。 这个可以通过getContent()获取出来。
(6)、把page放在"page"属性里,跳转到listCategory.jsp

m.addAttribute("page", page);
return "listCategory";

2、listCategory.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>   
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>查看分类</title>
</head>
<body>
	<div style="width: 500px; margin: 20px auto; text-align: center">
		<table align='center' border='1' cellspacing='0'>
			<tr>
				<td>id</td>
				<td>name</td>
				<td>编辑</td>
				<td>删除</td>
			</tr>
			<c:forEach items="${page.content}" var="c" varStatus="st">
				<tr>
					<td>${c.id}</td>
					<td>${c.name}</td>
					<td><a href="editCategory?id=${c.id}">编辑</a></td>
					<td><a href="deleteCategory?id=${c.id}">删除</a></td>
				</tr>
			</c:forEach>

		</table>
		<br>
		<div>
			<a href="?start=0">[首 页]</a> <a href="?start=${page.number-1}">[上一页]</a>
			<a href="?start=${page.number+1}">[下一页]</a> <a
				href="?start=${page.totalPages-1}">[末 页]</a>
		</div>
		<br>
		<form action="addCategory" method="post">

			name: <input name="name"> <br>
			<button type="submit">提交</button>

		</form>
</body>
</html>

3、editCategory.jsp
修改分类:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改</title>
</head>
<body>
	<div style="margin: 0px auto; width: 500px">

		<form action="updateCategory" method="post">

			name: <input name="name" value="${c.name}"> <br> <input
				name="id" type="hidden" value="${c.id}">
			<button type="submit">提交</button>

		</form>
	</div>
</body>
</html>

4、运行
由于采用的是热部署,直接访问
Here Insert Picture DescriptionHere Insert Picture Description5、最后再加一点JPA的拓展:自定义简单查询
自定义的简单查询就是根据方法名来自动生成 SQL,主要的语法是findXXBy,readAXXBy,queryXXBy,countXXBy, getXXBy后面跟属性名称:

Category findByCategoryName(String name);

也使用一些加一些关键字And 、 Or

Category findByCategoryNameOrId(String name,int id);

JPA同样可以实现复杂查询——分页查询、限制查询,
自定义SQL查询
多表查询
直接参考,用时再查:
Spring Boot(五):Spring Boot Jpa 的使用
Spring Data JPA - Reference Documentation

参考:
【1】、http://tengj.top/2017/03/13/springboot5/
【2】、http://how2j.cn/k/springboot/springboot-jsp/1647.html#nowhere
【3】、https://blog.csdn.net/wujiaqi0921/article/details/78789087
【4】、https://blog.csdn.net/forezp/article/details/70545038
【5】、http://www.ityouknow.com/springboot/2016/08/20/spring-boot-jpa.html

Guess you like

Origin blog.csdn.net/sinat_40770656/article/details/89483485