我有一个抽象实体。
@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;
}
还有一个通用的存储库接口(interface):
@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。
谢谢,
阿尔西
最佳答案
您的存储库类型不正确,请将其更改为。
@NoRepositoryBean
public interface IRepository<Entity extends AbstractEntity> extends Repository<Entity, Long> {
}
public interface ARepository extends IRepository<A> {
}
public interface BRepository extends IRepository<B> {
}
关于Spring 数据 jpa 继承-每个类的表不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36730706/