假设我们有一个包含 10 个变量的持久实体对象,如果我这样做,例如 repository.read(id)
或 repository.findById(id)
我会返回一个实体对象,其中包含从存储库设置的每个变量。
是否有任何方法使用 JPAQuery 或 EntityManager 或任何其他可能的方式,我可以在存储库上进行调用并返回实体对象,但也无需获取特定变量?
我尝试了以下操作,但它似乎没有做任何事情,仍然将 Set 带到响应中:
JPAQuery<Fruit> query = new JPAQuery<>(entityManager);
QFruit fruit = QFruit.Fruit;
Set<Apple> apple = new HashSet<Apple>();
query.select(fruit).from(fruit).where(fruit.id.eq(fruitId))
.createQuery().getParameters().remove(apple);
return query.fetchOne();
最佳答案
您可以使用任何自定义 POJO 来获取结果并指定选择的内容。
https://docs.oracle.com/html/E13946_05/ejb3_langref.html#ejb3_langref_constructor
public interface AppleRepository extends CrudRepository<Apple, Long> {
@Query("SELECT new com.mypackage.Apple(a.field1, a.field2) FROM " +
" Apple a ")
List<Apple> findCustomApples();
}
另一种方法是使任何特定列延迟加载。您可以通过注释来做到这一点。
关于java - 如何使用查询从存储库读取实体的特定变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56565570/