Reputation: 127
I have an abstract entity.
@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;
}
And 2 concrete implementations of this class:
Class 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;
}
Class 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;
}
And a common repository 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);
}
And each class has it's own repository which extends the generic repository:
public interface ARepository extends IRepository {
}
public interface BRepository extends IRepository {
}
When I invoke findAll() on ARespository, I get the records in both ARepository and BRepository. Since, the inheritance type is specified as TABLE_PER_CLASS, I assumed that a findAll() would only pick records from that table. I even added a query to the findAll() method to detect entity type and pick records appropriately, but this doesn't seem to be doing anything. Is there something I'm missing here?
I'm using Hibernate as my underlying persistence framework and am working on HSQLDB.
Thanks,
Aarthi
Upvotes: 3
Views: 2317
Reputation: 5503
The typing of your repositories is incorrect change it to.
@NoRepositoryBean
public interface IRepository<Entity extends AbstractEntity> extends Repository<Entity, Long> {
}
public interface ARepository extends IRepository<A> {
}
public interface BRepository extends IRepository<B> {
}
Upvotes: 4