對于一般的spring JpaRepository DAO(沒有spring-boot),如果介面擴展了一個自定義介面,spring會把介面方法誤認為是物件的屬性。
例如
interface ILocalDateTime {
fun getLocalDateTime() : LocalDateTime
}
interface UserDaoCustom : ILocalDateTime {
// query functions skipped
}
interface UserDao : JpaRepository<User, Long>, UserDaoCustom
class UserImpl : UserDaoCustom {
@PersistenceContext
private lateinit var em: EntityManager
override fun getLocalDateTime(): LocalDateTime {
return LocalDateTime.now()
}
// query functions skipped
}
這是一個簡化的UserDao. UserDaoCustomextendsILocalDateTime其中包含一個方法getLocalDateTime。
注意:localDateTime不是一個欄位User。
在運行時,JpaRepository將錯誤getLocalDateTime(或localDateTime?)作為User's field ,并拋出這樣的例外:
Caused by: org.springframework.data.repository.query.QueryCreationException:
Could not create query for public abstract java.time.LocalDateTime foo.ILocalDateTime.getLocalDateTime()!
Reason: Failed to create query for method public abstract java.time.LocalDateTime foo.ILocalDateTime.getLocalDateTime()!
No property getLocalDateTime found for type User!;
nested exception is java.lang.IllegalArgumentException:
Failed to create query for method public abstract java.time.LocalDateTime foo.ILocalDateTime.getLocalDateTime()!
No property getLocalDateTime found for type User!
環境 :
Kotlin 1.6.20
Spring 5.3.19
spring-data-jpa 2.5.11
如何解決這個問題呢 ?(能夠或不能修改ILocalDateTime的代碼)
謝謝。
uj5u.com熱心網友回復:
我認為這是關于命名以及 Spring 如何獲取存盤庫擴展的實作。
TLDR;
將實作的名稱從 更改UserImpl為UserDaoCustomImpl。
我已經檢查了類似的設定,并且使用您的命名失敗并出現完全相同的錯誤,但是將其命名為“正確”使其按預期作業
public interface ILocalDateTime {
LocalDateTime getLocalDateTime();
}
@Repository
public interface UserDao extends UserDaoCustom, JpaRepository<User, Long> {
}
public interface UserDaoCustom extends ILocalDateTime{
}
@Repository
public class UserDaoCustomImpl implements UserDaoCustom {
@Override
public LocalDateTime getLocalDateTime() {
return LocalDateTime.now();
}
}
和測驗
@ExtendWith(SpringExtension.class)
@DataJpaTest
class UserRepositoryTest {
@Autowired
private UserDao userDao;
@Test
public void savesUser() {
userDao.save(new User());
}
@Test
public void bazzinga() {
assert userDao.getLocalDateTime() != null;
System.out.println("Bazzinga!" userDao.getLocalDateTime());
}
}
產量

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/467289.html
