休眠获取实体子集

时间:2018-11-06 18:15:25

标签: hibernate jpa inheritance spring-data-jpa spring-data

在一个项目中,我有2个REST控制器,一个打算供第三方使用,另一个打算供内部人员使用。两个控制者都返回相同的实体,但是第三方获得内部人员看到的内容的过滤子集。过滤是基于实体的实体类型字段完成的。

我当前的实现如下

@Entity
@Table("TABLENAME")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorFormula("0")
@DiscriminatorValue("0")
public class Entity {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EntitySeq")
    @SequenceGenerator(name = "EntitySeq", sequenceName = "ENTITY_SEQ", allocationSize = 20)
    private Long id;

    //@Column("ENTITY_TYPE")
    //private EntityType entityType; //EntityType is an enumerator
}

@Entity
@Table("TABLENAME")
@Where("ENTITY_TYPE in ('A', 'B', 'C')
@DiscriminatorValue("00")   //Found at https://stackoverflow.com/questions/6572814/single-table-inheritance-without-discriminator-column
public class LimitedEntity extends Entity {}

存储库的编写方式如下:

public interface EntityRepository<T extends Entity> extends PagingAndSortingRepository<T, long> {
    List<T> findAll();
    List<T> findAll(Date from, Date to, Pageable pageable);

}

为了测试所有这些,我编写了如下测试:

@RunWith(SpringRunner.class)
@DataJpaTest
@ActiveProfiles({"local", "h2db"})
public class EntityRepositoryTest {
    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private EntityRepository<Entity> entityEntityRepository;

    @Autowired
    private EntityRepository<LimitedEntity> limitedEntityEntityRepository;

    @Before
    public void setup() {
        //Insert a record in the database for each possible value of entityType
    }

    @Test
    public void vacatureTypeFilterTest() {
        Date from = new GregorianCalendar(2018, 11, 5).getTime();
        Date to = new GregorianCalendar(2018, 11, 6).getTime();

        Assertions.assertThat(entityEntityRepository.countAllVacatures(from , to)).isEqualTo(EntityType.values().length);
        Assertions.assertThat(limitedEntityEntityRepository.countAllVacatures(from , to)).isEqualTo(3);
    }
}

正如测试中所写,我期望结果分别为9和3,但事实证明它们均为9。

为什么这不能正常工作?进行全局过滤的正确方法是什么?

0 个答案:

没有答案