Spring JPA:BaseEntity 未映射

Posted

技术标签:

【中文标题】Spring JPA:BaseEntity 未映射【英文标题】:Spring JPA: BaseEntity is not mapped 【发布时间】:2020-07-25 10:25:03 【问题描述】:

我正在与JPA Persistence 合作开展Spring Boot 项目。 我有一个基本实体类,例如:

@MappedSuperclass
@EntityListeners(AuditingEntityListener::class)
@Access(AccessType.FIELD)
abstract class BaseEntity<T: Serializable> : Persistable<T> 

    @Id @GeneratedValue
    private var id: T? = null
    // ...

实体类如:

@Entity
@Where(clause = "deleted = false")
class User(
    @Column
    val username: String,
    @Column
    val password: String,
    //...
) : BaseEntity<Long>()

我不想从数据库中物理删除记录,所以我添加了一个 BaseRepository 类,并重写了 deleteById() 方法,如下所示:

interface BaseRepository<T : BaseEntity<Long>?, ID> : JpaRepository<T, ID>, JpaSpecificationExecutor<T> 

    @Modifying
    @Query("update ##entityName o set o.deleted = true where o.id = ?1")
    override fun deleteById(@NonNull id: ID)
 

现在运行项目后出现此错误:

Caused by: org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'baseRepository': Invocation of init method failed; 
nested exception is java.lang.IllegalArgumentException: 
Validation failed for query for method
public abstract void com.example.repo.BaseRepository.deleteById(java.lang.Object)!

有什么想法吗?

【问题讨论】:

【参考方案1】:

我找到了解决方案。使用 @NoRepositoryBean 注释对 BaseRepository 进行注释。这确保 Spring Data JPA 不会尝试为 BaseRepository 接口创建实现:

@NoRepositoryBean 
interface BaseRepository<T : BaseEntity<Long>?, ID> : JpaRepository<T, ID>, JpaSpecificationExecutor<T> 
     // ...

【讨论】:

以上是关于Spring JPA:BaseEntity 未映射的主要内容,如果未能解决你的问题,请参考以下文章