https://blog.csdn.net/blueheart20/article/details/78227473?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~aggregatepage~first_rank_ecpm_v1~rank_v31_ecpm-2-78227473.pc_agg_new_rank&utm_term=jpa%E8%AE%BE%E7%BD%AE%E6%9C%80%E5%A4%A7%E6%9F%A5%E8%AF%A2%E8%AE%B0%E5%BD%95%E6%95%B0&spm=1000.2123.3001.4430
引言:JPA与SpringData中提供了诸多非常便利的方法,这里以如何以不书写SQL的方式来实现单条记录的查询。
repositories.limit-query-result
这个标题为Spring Data提供了内置功能,这些查询方法需要使用first/top等关键词,这两个关键词是彼此可以替代的。 可选的数字值用以表示最大可以返回的记录条数,一般都是放在first/top的右边。
Example 15. Limiting the result size of a query with Top and First
其中也是支持Distinct关键词的,限定词也可以支持Optional之类的关键词。 参考资料: Spring Data JPA - Reference Documentation
程序示例
实体类:
@Entity @Table(name="t_user") @Data @EqualsAndHashCode(callSuper=true) public class UserEntity extends BaseEntity { @Column(name="pin_key") private String userKey; @Column(name="device_type") private String deviceType; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "created_time") @Temporal(TemporalType.TIMESTAMP) private Date createdTime; @Column(name = "updated_time") @Temporal(TemporalType.TIMESTAMP) @Version private long version; }123456789101112131415161718192021222324
Repository的代码:
@Repository public interface UserRepository extends JpaRepository<UserEntity, Long> { public UserEntity findFirstByOrderByCreatedTimeDesc(); }1234
Service的示例代码:
@Slf4j @Service public class DemoService { @Autowired private UserRepository userRepo; ..... public UserEntity getLatestUser() { return this.userRepo.findFirstByOrderByCreatedTimeDesc(); } }1234567891011
Controller的代码示例:
@Slf4j @RestController public class TestController { @Autowired private DemoService demoService; @GetMapping("/test/user") public String getUser() { UserEntity user = this.userRepo.findFirstByOrderByCreatedTimeDesc(); log.info("userInfo:" + ReflectionToStringBuilder.toString(user)); return user.toString(); } }1234567891011121314
然后直接在浏览器打开连接就可以直接访问。 其余相关的配置项由于篇幅所限,就不在一一的黏贴拷贝了。
总结
Spring Data提供了大量非常好用的缺省实现,对于开发者而言直接使用即可,从而可以提升开发效率,充分体现瑞士军刀的锋利与效率。