我在我的项目中使用了Spring 5。直到今天,还有可用的方法CrudRepository#findOne
.
但是在下载最新快照后,它突然消失了!是否有任何参考资料表明该方法现在不可用?
我的依赖列表:
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
repositories {
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}
dependencies {
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
runtime 'com.h2database:h2:1.4.194'
}
更新:
似乎这种方法已被替换为CrudRepository#findById
请参阅 DATACMNS-944,它与此提交相关联,该提交具有以下重命名
╔═════════════════════╦═══════════════════════╗
║ Old name ║ New name ║
╠═════════════════════╬═══════════════════════╣
║ findOne(…) ║ findById(…) ║
╠═════════════════════╬═══════════════════════╣
║ save(Iterable) ║ saveAll(Iterable) ║
╠═════════════════════╬═══════════════════════╣
║ findAll(Iterable) ║ findAllById(…) ║
╠═════════════════════╬═══════════════════════╣
║ delete(ID) ║ deleteById(ID) ║
╠═════════════════════╬═══════════════════════╣
║ delete(Iterable) ║ deleteAll(Iterable) ║
╠═════════════════════╬═══════════════════════╣
║ exists() ║ existsById(…) ║
╚═════════════════════╩═══════════════════════╝
注意findById
不是 findOne
的精确替代品,它返回一个Optional
而不是null
。
由于对新的 Java 不是很熟悉,我花了一点时间才弄清楚,但这将findById
行为变成了findOne
行为:
return rep.findById(id).orElse(null);
旧findOne()
方法有数百种用法。我们最终没有开始进行大规模的重构,而是创建了以下中间接口,并让我们的存储库对其进行扩展,而不是直接扩展JpaRepository
@NoRepositoryBean
public interface BaseJpaRepository<T, ID> extends JpaRepository<T, ID> {
default T findOne(ID id) {
return (T) findById(id).orElse(null);
}
}
务实的转换
旧方式:
Entity aThing = repository.findOne(1L);
新方式:
Optional<Entity> aThing = repository.findById(1L);
另一种方式。添加@Query
。即使我更愿意消费Optional
:
@Repository
public interface AccountRepository extends JpaRepository<AccountEntity, Long> {
@Query("SELECT a FROM AccountEntity a WHERE a.id =? 1")
public AccountEntity findOne(Long id);
}