SpringBoot implements persistence layer support: JPA

Two, SpringBoot persistence layer support

Learning website recommendation: How2java

1. JPA concept

​ JPA (Java Persistence API) is a Java persistence specification officially proposed by Sun to facilitate the operation of the database.
​ The real work may be Hibernate, TopLink, etc. different vendors that implement the JPA specification, the default is Hibernate.

2. JPA configuration

  1. Create database and table, prepare data

    create database how2java;
    
    use how2java;
    CREATE TABLE category_ (
      id int(11) NOT NULL AUTO_INCREMENT,
      name varchar(30),
      PRIMARY KEY (id)
    ) DEFAULT CHARSET=UTF8;
    
    insert into category_ values(null,'category 1');
    insert into category_ values(null,'category 2');
    insert into category_ values(null,'category 3');
    insert into category_ values(null,'category 4');
    
  2. Modify application.properties

    Configure related items to connect to the database

    spring.mvc.view.prefix=/WEB-INF/jsp/
    spring.mvc.view.suffix=.jsp
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8
    spring.datasource.username=root
    spring.datasource.password=admin
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.jpa.properties.hibernate.hbm2ddl.auto=update
    
  3. Modify pom.xml

    Add configuration to the dependencies tag in this file, adding support for Mysql and Jpa

            <!-- 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> 
    
  4. Create Category, CategoryDAO, CategoryController respectively

    • Category

      Add a package: com.how2java.springboot.pojo, and then create the entity category Category.
      The @Entity annotation indicates that this is an entity class
      @Table(name = "category_") indicates that the table name corresponding to this class is category_. Note that the underscore
      @Id indicates the primary key
      @GeneratedValue(strategy = GenerationType.IDENTITY) indicates the self-growth mode
      @Column( name = "id") indicates the corresponding database field name

      package com.how2java.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;
       
      @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;
          }
           
      }
      
    • CategoryDAO

      Add a package: com.how2java.springboot.dao, and then create the dao interface; CategoryDAO inherits JpaRepository, and provides generic <Category,Integer> to indicate that this is a DAO for the Category class, and Integer indicates that the primary key is of type Integer.
      JpaRepository, the parent interface, provides a series of queries such as CRUD, paging, etc., which can be used directly without secondary development.

      package com.how2java.springboot.dao;
      import org.springframework.data.jpa.repository.JpaRepository;
      import com.how2java.springboot.pojo.Category;
       
      public interface CategoryDAO extends JpaRepository<Category,Integer>{
              
              
       
      }
      
    • CategoryController

      Add a package: com.how2java.springboot.web , and then create the CategoryController class.

      1. Accept listCategory mapping
      2. Then get all the classification data
      3. Then put it into the Model
      4. Jump to listCategory.jsp
      package com.how2java.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";
          }
           
      }
      
  5. Create listCategory.jsp

    Traverse the collection (cs) passed by CategoryController

    <%@ 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>
    
  6. Restart test

    Since the dependency on the jar package is added to pom.xml, and the hot deployment of Springboot cannot work, you need to restart it manually here:

    Then visit the test address:

    listCategory

Guess you like

Origin blog.csdn.net/weixin_40849588/article/details/95486758