Spring Date jpa 获取最新一条数据实例代码

网友投稿 1008 2023-03-27

Spring Date jpa 获取最新一条数据的实例代码

Spring Date jpa 获取最新一条数据的实例代码

#Repository

import test.demo.domain.entity.TestEntity;

import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;

import org.springframework.stereotype.Repository;

@Repository

public interface TestEntityRepository extends JpaRepositoryImplementation {

}

#Service

import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotBlank;

@Validated

public interface TestService {

/**

* 获取账号最新的一个数据(指单个字段,例如最新时间,最新年龄等)

* @param username

* @return

*/

String findLastage(@NotBlank String username);

}

#ServiceImpl

import test.demo.domain.entity.TestEntity;

import test.demo.repository.TestEntityRepository;

import test.demo.service.TestService;

import org.springframework.beans.factory.annotatihttp://on.Autowired;

import org.springframework.data.domain.PageRequest;

import org.springframework.data.domain.Sort;

import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

import java.util.List;

@Service

public class TestServiceImpl implements TestService {

@Autowired

private TestEntityRepository testEntityRepository;

@Override

public String findLastAge(String username) {

Sort createTime = new Sort(Sort.Direction.DESC, "createTime");

PageRequest of = PageRequest.of(0, 1, createTime);

List testEntities= testEntityRepository.findAll(((root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.and(

criteriaBuilder.equal(root.get("age"), age),

criteriaBuilder.lessThan(root.get("expiredTime"), LocalDateTime.now())

)));

if (testEntities.isEmpty()){

return null;

}

String age = TestEntities.get(0).getCode();

return age;

}

}

Entity这里就不写了,很普通,只说重点!

看下官方文档的解释:

补充知识:【spring data jpa】根据一个时间字段 查询 时间段的处理方法

处理方法 包含结束时间00.00.00

Date createDate = boxCodeLog.getCreateDate();

if (createDate != null){

LocalDate localDate=createDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

localDate = localDate.plusDays(1);

Date endDate = java.sql.Date.valueOf(localDate);

predicates.add(cb.between(root.get("createDate"),createDate,endDate));

}

包含结束时间 23.59.59

Date createDate = receipt.getCreateDate();

if (createDate != null){

LocalDate localDate=createDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

localDate = localDate.plusDays(1);

Date endDate = new Date(java.sql.Date.valueOf(localDate).getTime()-1L);

predicates.add(cb.between(root.get("createDate"),createDate,endDate));

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:浅谈Synchronized和Lock的区别
下一篇:小程序页面跳转(小程序怎么打开)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~