JPA, which stands for the Java Persistence API, is a JDK 5.0 annotation or XML that describes object-relational table mappings and persists runtime entity objects to a database.

  • SpringBoot uses SpringDataJPA to perform CRUD operations. Data storage and access are the most core of the key part, now many enterprises use mainstream databases, such as relational databases: MySQL, Oracle, SQLServer. Non-relational database: Redis, mongodb, etc.
  • Spring Data JPA is a sub-project of Spring Data that significantly reduces the code required to manipulate JPA by providing a JPA-based Repository.

1. Import related dependency files and configure them

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

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
Copy the code
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url:
    username:
    password:
  jpa:
    database: mysql
    SQL statements are displayed in the log
    show-sql: true
    hibernate:
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
Copy the code

2. Use of JPA

Step 1: Create a new entity class and add JPA annotations

@Data
@AllArgsConstructor
@NoArgsConstructor

@Entity
@Table(name = "article")
public class Article implements Serializable {

    @Id
    @GeneratedValue
    @Column(name = "a_id")
    private Integer aId;
    @Column(name = "article_title")
    private String articleTitle;
    @Column(name = "article_content")
    private String articleContent;
    @Column(name = "head_image")
    private String headImage;
    @Column(name = "article_author")
    private String articleAuthor;
    @Column(name = "type_number")
    private Integer typeNumber;
    @Column(name = "pageviews")
    private Integer pageViews;
    @Column(name = "create_time")
    private String createTime;
    @Column(name = "is_state")
    private Integer isState;
    
}
Copy the code

Step 2: Create the ArticleDao interface

/** * JpaRepository
      
        provides a simple data manipulation interface * Article entity class type * Integer primary key type ** JpaSpecificationExecutor
       
         provides a complex query interface * Article Entity class type * * Serializable */
       
      ,id>
@Repository
public interface ArticleDao extends JpaRepository<Article.Integer>,JpaSpecificationExecutor<Article>,Serializable{

    // There is no code here, notice there is no code..........

}
Copy the code

Step 3: Test

@SpringBootTest
class Springboot07JpaApplicationTests {

    @Autowired
    private ArticleDao articleDao;

    @Test
    void contextLoads(a) { List<Article> articleList = articleDao.findAll(); articleList.forEach(System.out::println); }}Copy the code

3. JPA query method command specification

The keyword Method named The SQL where words
And findByNameAndPwd where name= ? and pwd =?
Or findByNameOrSex where name= ? or sex=?
Is,Equals findById,findByIdEquals where id= ?
Between findByIdBetween where id between ? and ?
LessThan findByIdLessThan where id < ?
LessThanEquals findByIdLessThanEquals where id <= ?
GreaterThan findByIdGreaterThan where id > ?
GreaterThanEquals findByIdGreaterThanEquals where id > = ?
After findByIdAfter where id > ?
Before findByIdBefore where id < ?
IsNull findByNameIsNull where name is null
isNotNull,NotNull findByNameNotNull where name is not null
Like findByNameLike where name like ?
NotLike findByNameNotLike where name not like ?
StartingWith findByNameStartingWith where name like ‘? % ‘
EndingWith findByNameEndingWith where name like ‘%? ‘
Containing findByNameContaining where name like ‘%? % ‘
OrderBy findByIdOrderByXDesc where id=? order by x desc
Not findByNameNot where name <> ?
In findByIdIn(Collection<? > c) where id in (?)
NotIn findByIdNotIn(Collection<? > c) where id not in (?)
True findByAaaTue where aaa = true
False findByAaaFalse where aaa = false
IgnoreCase findByNameIgnoreCase where UPPER(name)=UPPER(?)

4. JPQL syntax generation

public interface StandardRepository extends JpaRepository<Standard.Long> {

    // JPA naming conventions
    List<Standard> findByName(String name);

    // Custom queries that do not follow naming conventions
    @Query("from Standard where name = ?" )
    Standard findByNamexxxx(String name);

    // Follow the naming conventions and execute multi-condition queries
    Standard findByNameAndMaxLength(String name, Integer maxLength);

    // Customize multi-condition query
    @Query("from Standard where name = ? 2 and maxLength = ? 1)"
    Standard findByNameAndMaxLengthxxx(Integer maxLength, String name);

    Mysql > select * from 'standard'
    @Query(value = "select * from T_STANDARD where C_NAME = ? and C_MAX_LENGTH = ?" , nativeQuery = true)
    Standard findByNameAndMaxLengthxx(String name, Integer maxLength);

    // fuzzy query
    Standard findByNameLike(String name);

    @Modifying // Indicates that the operation is an update
    @Transactional // Transaction annotations
    @Query("delete from Standard where name = ?" )
    void deleteByName(String name);

    @Modifying // Indicates that the operation is an update
    @Transactional // Transaction annotations
    @Query("update Standard set maxLength = ? where name = ?" )
    void updateByName(Integer maxLength, String name);
}
Copy the code

5. JPA URUD example

Modle: Article. Java

@Data
@AllArgsConstructor
@NoArgsConstructor

@Entity
@Table(name = "article")
public class Article implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "a_id")
    private int aId;
    @Column(name = "article_title")
    private String articleTitle;
    @Column(name = "article_content")
    private String articleContent;
    @Column(name = "head_image")
    private String headImage;
    @Column(name = "article_author")
    private String articleAuthor;
    @Column(name = "type_number")
    private int typeNumber;

    private int pageviews;

    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "create_time")
    private Date createTime;
    @Column(name = "is_state")
    private int isState;
}
Copy the code

The dao: ArticleDao. Java

public interface ArticleDao extends JpaRepository<Article.Integer>, JpaSpecificationExecutor<Article>, Serializable {

    List<Article> findByArticleTitleContaining(String keywords);

    // Custom methods
    @Query("select art from Article art where art.articleTitle like %? 1% or art.articleContent like %? 1%)"
    Page<Article> findByLike(String keywords, Pageable pageable);
}
Copy the code

Service: ArticleService. Java

public interface ArticleService {

    Page<Article> findByLike(String keywords, int page, int pageSize);

    public void delArticle(int aId);

    public void updateArticle(Article article);

    public void addArticle(Article article);
}
Copy the code

ServiceImpl: ArticleServiceImpl. Java

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleDao articleDao;

    @Override
    public Page<Article> findByLike(String keywords, int page, int pageSize) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        PageRequest pageable = PageRequest.of(page - 1, pageSize, sort);
        Page<Article> pageResult = articleDao.findByLike(keywords, pageable);
        return pageResult;
    }

    @Override
    public void delArticle(int aId) {
        articleDao.deleteById(aId);
    }

    @Override
    public void updateArticle(Article article) {
        articleDao.save(article);
    }

    @Override
    public void addArticle(Article article) { articleDao.save(article); }}Copy the code

Controller: ArticleController. Java

@RestController
@api (value = "interface ", description =" interface ")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @GetMapping("Article")
    public ResponseData<Article> selAllArticle(
        @RequestParam(value = "keywords", required = true, defaultValue = "") String keywords,
        @RequestParam(value = "page", required = true, defaultValue = "1") Integer page,
        @RequestParam(value = "pageSize", required = true, defaultValue = "10") Integer pageSize) {

        Page<Article> pageResult = articleService.findByLike(keywords, page, pageSize);
        ResponseData<Article> rd = new ResponseData<Article>(200."success", pageResult.getTotalElements(), pageResult.getContent());
        return rd;
    }
    
    @DeleteMapping("Article/{aId}")
    public void delArticleById(@PathVariable int aId) {
        articleService.delArticle(aId);
    }
    
    @PutMapping("Article")
    public void updateArticleById(@RequestBody Article article) {
        articleService.updateArticle(article);
    }
    
    @PostMapping("Article")
    public void addArticleById(@RequestBody Article article) { articleService.addArticle(article); }}Copy the code

6. JPA implements paging and fuzzy query

Modle: Article. Java

@Data
@AllArgsConstructor
@NoArgsConstructor

@Entity
@Table(name = "article")
public class Article implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "a_id")
    private int aId;
    @Column(name = "article_title")
    private String articleTitle;
    @Column(name = "article_content")
    private String articleContent;
    @Column(name = "head_image")
    private String headImage;
    @Column(name = "article_author")
    private String articleAuthor;
    @Column(name = "type_number")
    private int typeNumber;

    private int pageviews;

    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "create_time")
    private Date createTime;
    @Column(name = "is_state")
    private int isState;
}
Copy the code

The dao: ArticleDao. Java

public interface ArticleDao extends JpaRepository<Article.Integer>, JpaSpecificationExecutor<Article>, Serializable {

    @Query("select art from Article art where art.articleTitle like %? 1% or art.articleContent like %? 1%)"
    Page<Article> findByLike(String keywords, Pageable pageable);
}
Copy the code

Service: ArticleService. Java

public interface ArticleService {

    Page<Article> findByLike(String keywords, int page, int pageSize);
}
Copy the code

ServiceImpl: ArticleServiceImpl. Java

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleDao articleDao;

    @Override
    public Page<Article> findByLike(String keywords, int page, int pageSize) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        PageRequest pageable = PageRequest.of(page - 1, pageSize, sort);
        Page<Article> pageResult = articleDao.findByLike(keywords, pageable);
        returnpageResult; }}Copy the code

Controller: ArticleController. Java

@RestController
@api (value = "interface ", description =" interface ")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @GetMapping("Article")
    public ResponseData<Article> selAllArticle(
        @RequestParam(value = "keywords", required = true, defaultValue = "") String keywords,
        @RequestParam(value = "page", required = true, defaultValue = "1") Integer page,
        @RequestParam(value = "pageSize", required = true, defaultValue = "10") Integer pageSize) {

        Page<Article> pageResult = articleService.findByLike(keywords, page, pageSize);
        ResponseData<Article> rd = new ResponseData<Article>(200."success", pageResult.getTotalElements(), pageResult.getContent());
        returnrd; }}Copy the code