如何在spring数据查询中获取insanceof对象

时间:2016-03-30 17:05:03

标签: java spring jpa spring-data instanceof

我有Item

@Getter
@Setter
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Item {
    @Id 
    private Long id;
    private String name;
}

这两个下一个类是Item

的子类
@Getter
@Setter
@Entity
public class RawMaterial extends Item {
    private String supplier;
}

@Getter
@Setter
@Entity
public class Product extends Item {
    private BigDecimal salePrice;
}

我还有一个Inventory类,其中Item为字段

@Getter
@Setter
@Entity
public class Inventory {
    @Id 
    private Long id;

    @ManyToOne 
    private Item item;
}

我的问题是如何获取 item字段的实例。有dtype的东西吗?

public interface InventoryDao extends JpaRepository<Inventory,Long> {

    @Query("FROM Inventory WHERE item instance of ?1")
    public List<Inventory> getInventoryByItem(Class klazz);

}

我需要做类似

的事情
List<Inventory> list = getInventoryByItem(Product.class);

1 个答案:

答案 0 :(得分:1)

我自己解决了。

public interface InventoryDao extends JpaRepository<Inventory,Long> {

    @Query("FROM Inventory WHERE TYPE(item.class) = ?1")
    public List<Inventory> getInventoryByItem(Class<? extends Item> klazz);

}