引言: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
User findFirstByOrderByLastnameAsc();
User findTopByOrderByAgeDesc();
Page queryFirst10ByLastname(String lastname, Pageable pageable);
Slice findTop3ByLastname(String lastname, Pageable pageable);
List findFirst10ByLastname(String lastname, Sort sort);
List findTop10ByLastname(String lastname, Pageable pageable);
其中也是支持Distinct关键词的,限定词也可以支持Optional之类的关键词。
参考资料: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.limit-query-result
程序示例
实体类:
@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;
}
Repository的代码:
@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {
public UserEntity findFirstByOrderByCreatedTimeDesc();
}
Service的示例代码:
@Slf4j
@Service
public class DemoService {
@Autowired
private UserRepository userRepo;
.....
public UserEntity getLatestUser() {
return this.userRepo.findFirstByOrderByCreatedTimeDesc();
}
}
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();
}
}
然后直接在浏览器打开连接就可以直接访问。
其余相关的配置项由于篇幅所限,就不在一一的黏贴拷贝了。
总结
Spring Data提供了大量非常好用的缺省实现,对于开发者而言直接使用即可,从而可以提升开发效率,充分体现瑞士军刀的锋利与效率。