Spring数据jpa继承 - 每个类的表不起作用

时间:2016-04-19 22:35:58

标签: spring hibernate jpa spring-data-jpa

我有一个抽象的实体。

@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
@EntityListeners(AuditingEntityListener.class)
public abstract class AbstractEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    protected long id;

    @CreatedBy
    protected String createdBy;

    @CreatedDate
    protected Date creationDate;

    @LastModifiedBy
    protected String modifiedBy;

    @LastModifiedDate
    protected Date lastModifiedDate;

}

这个类的2个具体实现:

A类:

@Entity
@Table(name = "A")
public class A extends AbstractEntity {

    @Column(name = "NAME", nullable = false)
    private String name;

    @Column(name = "PRIORITY", nullable = false)
    private int priority;
}

B组:

@Entity
@Table(name = "B")
public class B extends AbstractEntity {

    @Column(name = "PLACE", nullable = false)
    private String place;

    @Column(name = "DISTANCE", nullable = false)
    private int distance;
}

一个公共存储库接口:

@NoRepositoryBean
public interface IRepository extends Repository<AbstractEntity, Long> {
    /**
     * Method to query by unique id/PK.
     * @param id
     * @return Entity with id "id"
     */
    @Query("select entity from #{#entityName} as entity where entity.id = ?1")
    public AbstractEntity findById(long id);

    /**
     * Insert method
     * @param abstractEntity
     * @return modified entity after insertion
     */
    public AbstractEntity save(AbstractEntity abstractEntity);

    /**
     * select all records from the table
     * @return list of all entities representing records in the table
     */
    @Query("select entity from #{#entityName} as entity")
    public List<AbstractEntity> findAll();

    /**
     * delete record by id
     * @param id
     */
    public void deleteById(long id);
}

每个类都有自己的存储库,扩展了通用存储库:

public interface ARepository extends IRepository {
}

public interface BRepository extends IRepository {
}

当我在ARespository上调用findAll()时,我会在ARepository和BRepository中获取记录。由于继承类型被指定为TABLE_PER_CLASS,我假设findAll()只从该表中选择记录。我甚至在findAll()方法中添加了一个查询来检测实体类型并适当地选择记录,但这似乎没有做任何事情。这里有什么我想念的吗?

我正在使用Hibernate作为我的底层持久性框架,并且正在使用HSQLDB。

谢谢,

Aarthi

1 个答案:

答案 0 :(得分:3)

您的存储库输入错误,请将其更改为。

@NoRepositoryBean
public interface IRepository<Entity extends AbstractEntity> extends Repository<Entity, Long> {

}

public interface ARepository extends IRepository<A> {

}

public interface BRepository extends IRepository<B> {

}