Directory
1. Create a project
2. Configure database connection information
3. Build entity data table
4. Create interface and service layer
5. Create the control layer
6. Overall project structure
7. Run the project
1. Create a project
2. Configure database connection information
jpa defaults to hibernate
server: port: 8888 spring: datasource: url: jdbc:mysql://localhost:3306/_spring_exam driver-class-name: com.mysql.cj.jdbc.Driver username: root password: root jpa: properties: hibernate: hbm2ddl: # Configuration properties of hibernate: automatically create, update, and verify data table structures auto: update # create/create-drop/update/validate dialect: org.hibernate.dialect.MySQL5InnoDBDialect show-sql: true # The console of the development tool displays sql thymeleaf: prefix: classpath:/templates/ cache: false
3. Build entity data table
@NotEmpty Unable to resolve symbol ‘NotEmpty’ Need to add dependency
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
package com.example.jpa.entity; import lombok.Data; import javax.persistence.*; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.Arrays; import java.util.List; /** * @author: fly * @Date: 2023-03-20 18:59 * @Description: Use jpa to build entity data table */ // declare class as entity @Entity //@Table(appliesTo = "article") When the class name is consistent with the data table name, it can be omitted @Data public class Article implements Serializable { @Id // table name This is a primary key of this class (table) // IDENTITY represents controlled by the database // AUTO means unified management by the Spring Boot application [When there are multiple tables, the self-increment value of the id does not necessarily start from 1] @GeneratedValue(strategy = GenerationType. IDENTITY) private Long id; // Specify the field name, if the field name is the same as the column name, it can be omitted @Column(nullable = false, unique = true, columnDefinition = "comment 'article title'") @NotEmpty(message = "The title cannot be empty") private String title; // enumeration type @Column(columnDefinition = "enum('picture','graphic','article')") private String type;// article type private Boolean available = Boolean. FALSE; @Size(min=0,max=20) private String keyword; @Size(max=255) private String description; @Column(nullable = false) private String body; // create virtual field @Transient private List<String> keywordLists; public List<String> getKeywordLists() { return Arrays.asList(this.keyword.trim().split("|")); } public void setKeywordLists(List<String> keywordLists) { this.keywordLists = keywordLists; } }
Run the project Automatically generate data tables
4. Create interface and service layer
Create ArticleRepository to inherit JpaRepository
package com.example.jpa.repository; import com.example.jpa.entity.Article; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; /** * @author: fly * @Date: 2023-03-21 9:25 * @Description: The persistence layer of the article */ @Repository public interface ArticleRepository extends JpaRepository<Article,Long>, JpaSpecificationExecutor<Article> { /** * Query articles by article id * @param id article id * @return article */ Article findById(long id); }
Service layer and its implementation class
ArticleService interface
package com.example.jpa.service; import com.example.jpa.entity.Article; import java.util.List; /** * @author: fly * @Date: 2023-03-21 9:53 * @Description: */ public interface ArticleService { /** * Get the list of articles * @return set of articles */ public List<Article> getArticleList(); /** * Find articles by id * @param id article id * @return article */ public Article findArticleById(long id); }
ArticleServiceImpl implementation class
package com.example.jpa.service.impl; import com.example.jpa.entity.Article; import com.example.jpa.repository.ArticleRepository; import com.example.jpa.service.ArticleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author: fly * @Date: 2023-03-21 9:56 * @Description: article service class */ @Service public class ArticleServiceImpl implements ArticleService { private ArticleRepository articleRepository; @Autowired public void setArticleRepository(ArticleRepository articleRepository) { this. articleRepository = articleRepository; } /** * Get all articles * @return all articles */ @Override public List<Article> getArticleList() { return articleRepository. findAll(); } /** * Find articles by id * @param id article id * @return article */ @Override public Article findArticleById(long id) { return articleRepository.findById(id); } }
5. Create a control layer
ArticleController class
package com.example.jpa.controller; import com.example.jpa.entity.Article; import com.example.jpa.repository.ArticleRepository; import lombok.extern.log4j.Log4j2; 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.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; /** * @author: fly * @Date: 2023-03-21 8:24 * @Description: The controller that handles the article */ @RestController @RequestMapping("/article") @Log4j2 public class ArticleController { private ArticleRepository articleRepository; @Autowired public void setArticleRepository(ArticleRepository articleRepository) { this. articleRepository = articleRepository; } @RequestMapping("") public ModelAndView articleList(@RequestParam(value = "start",defaultValue = "0") Integer start, @RequestParam(value = "limit",defaultValue = "10") Integer limit) { start = start < 0 ? 0 : start; Sort sort = Sort.by(Sort.Direction.DESC,"id"); Pageable pageable = PageRequest.of(start,limit,sort); Page<Article> page = articleRepository. findAll(pageable); ModelAndView modelAndView = new ModelAndView("article/list"); modelAndView.addObject("page",page); return modelAndView; } @RequestMapping("/{id}") public ModelAndView getArticle(@PathVariable Integer id) { Article article = articleRepository.findById(id); ModelAndView modelAndView = new ModelAndView("article/show"); log. info(article); modelAndView.addObject("article",article); return modelAndView; } }
6. Overall project structure
7. Run the project
code address
Reference GitHub address: GitHub – xiuhuai/Spring-Boot-Book
08 folder: jpa operation database