您好,登錄后才能下訂單哦!
本篇文章為大家展示了Spring Date jpa 實(shí)現(xiàn)獲取最新一條數(shù)據(jù)的方法,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。
#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<TestEntity,Integer> { }
#Service
import org.springframework.validation.annotation.Validated; import javax.validation.constraints.NotBlank; @Validated public interface TestService { /** * 獲取賬號(hào)最新的一個(gè)數(shù)據(jù)(指單個(gè)字段,例如最新時(shí)間,最新年齡等) * @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.annotation.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<TestEntity> 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這里就不寫了,很普通,只說(shuō)重點(diǎn)!
看下官方文檔的解釋:
補(bǔ)充知識(shí):【spring data jpa】根據(jù)一個(gè)時(shí)間字段 查詢 時(shí)間段的處理方法
處理方法 包含結(jié)束時(shí)間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)); }
包含結(jié)束時(shí)間 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)); }
上述內(nèi)容就是Spring Date jpa 實(shí)現(xiàn)獲取最新一條數(shù)據(jù)的方法,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。