Spring Data JPA的使用

JPA顾名思义就是Java Persistence API的意思,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。

  • SpringBoot使用SpringDataJPA完成CRUD操作. 数据的存储以及访问都是最为核心的关键部分,现在有很多企业采用主流的数据库,如关系型数据库:MySQL,Oracle,SQLServer。非关系型数据库:redis,mongodb等.
  • Spring Data JPA 是Spring Data 的一个子项目,它通过提供基于JPA的Repository极大了减少了操作JPA的代码。

1、导入相关依赖并配置文件

<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>
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url:
    username:
    password:
  jpa:
    database: mysql
    # 日志中显示sql语句
    show-sql: true
    hibernate:
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

2、JPA使用

步骤一:新建实体类并添加JPA注解

@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;
    
}

步骤二:新建接口ArticleDao

/**
 * JpaRepository<T,ID>  提供简单的数据操作接口
 *     Article 实体类类型
 *     Integer 主键类型
 *
 * JpaSpecificationExecutor<T> 提供复杂查询接口
 *     Article 实体类类型
 *
 * Serializable 序列化
 */
@Repository
public interface ArticleDao extends JpaRepository<Article,Integer>,JpaSpecificationExecutor<Article>,Serializable{

    //这里没有代码,注意没有代码..........

}

步骤三:测试

@SpringBootTest
class Springboot07JpaApplicationTests {

    @Autowired
    private ArticleDao articleDao;

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

}

3、JPA查询方法命令规范

关键字方法命名sql where字句
AndfindByNameAndPwdwhere name= ? and pwd =?
OrfindByNameOrSexwhere name= ? or sex=?
Is,EqualsfindById,findByIdEqualswhere id= ?
BetweenfindByIdBetweenwhere id between ? and ?
LessThanfindByIdLessThanwhere id < ?
LessThanEqualsfindByIdLessThanEqualswhere id <= ?
GreaterThanfindByIdGreaterThanwhere id > ?
GreaterThanEqualsfindByIdGreaterThanEqualswhere id > = ?
AfterfindByIdAfterwhere id > ?
BeforefindByIdBeforewhere id < ?
IsNullfindByNameIsNullwhere name is null
isNotNull,NotNullfindByNameNotNullwhere name is not null
LikefindByNameLikewhere name like ?
NotLikefindByNameNotLikewhere name not like ?
StartingWithfindByNameStartingWithwhere name like '?%'
EndingWithfindByNameEndingWithwhere name like '%?'
ContainingfindByNameContainingwhere name like '%?%'
OrderByfindByIdOrderByXDescwhere id=? order by x desc
NotfindByNameNotwhere name <> ?
InfindByIdIn(Collection<?> c)where id in (?)
NotInfindByIdNotIn(Collection<?> c)where id not in (?)
TruefindByAaaTuewhere aaa = true
FalsefindByAaaFalsewhere aaa = false
IgnoreCasefindByNameIgnoreCasewhere UPPER(name)=UPPER(?)

4、JPQL语法生成

public interface StandardRepository extends JpaRepository<Standard, Long> {

    // JPA的命名规范
    List<Standard> findByName(String name);

    // 自定义查询,没有遵循命名规范
    @Query("from Standard where name = ?")
    Standard findByNamexxxx(String name);

    // 遵循命名规范,执行多条件查询
    Standard findByNameAndMaxLength(String name, Integer maxLength);

    // 自定义多条件查询
    @Query("from Standard where name = ?2 and maxLength = ?1")
    Standard findByNameAndMaxLengthxxx(Integer maxLength, String name);

    // 使用”标准”SQL查询,以前mysql是怎么写,这里继续
    @Query(value = "select * from T_STANDARD where C_NAME = ? and C_MAX_LENGTH = ?",
           nativeQuery = true)
    Standard findByNameAndMaxLengthxx(String name, Integer maxLength);

    // 模糊查询
    Standard findByNameLike(String name);

    @Modifying // 代表本操作是更新操作
    @Transactional // 事务注解
    @Query("delete from Standard where name = ?")
    void deleteByName(String name);

    @Modifying // 代表本操作是更新操作
    @Transactional // 事务注解
    @Query("update Standard set maxLength = ? where name = ?")
    void updateByName(Integer maxLength, String name);
}

5、JPA URUD示例

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;
}

dao:ArticleDao.java

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

    List<Article> findByArticleTitleContaining(String keywords);

    //自定义方法
    @Query("select art from Article art where art.articleTitle like %?1% or art.articleContent like %?1%")
    Page<Article> findByLike(String keywords, Pageable pageable);
}

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);
}

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);
    }
}

controller:ArticleController.java

@RestController
@Api(value = "文章的接口", description = "文章的接口")
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);
    }
}

6、JPA实现分页和模糊查询

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;
}

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);
}

service:ArticleService.java

public interface ArticleService {

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

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;
    }
}

controller:ArticleController.java

@RestController
@Api(value = "文章的接口", description = "文章的接口")
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;
    }
}
最后修改:2021 年 10 月 05 日 02 : 46 AM
如果觉得我的文章对你有用,请随意赞赏