Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring JPQL特殊查询_Spring_Hibernate_Jakarta Ee_Jpa_Jpql - Fatal编程技术网

Spring JPQL特殊查询

Spring JPQL特殊查询,spring,hibernate,jakarta-ee,jpa,jpql,Spring,Hibernate,Jakarta Ee,Jpa,Jpql,我有两个实体bean: @Entity public class User { @Id @GeneratedValue private Long id; @OneToMany(mappedBy="user", cascade = CascadeType.ALL) private List<Comment> comments = new ArrayList<Comment>(); //SOME OTHER CLASS VARIABLES

我有两个实体bean:

@Entity
public class User {
   @Id
   @GeneratedValue
   private Long id;
   @OneToMany(mappedBy="user", cascade = CascadeType.ALL)
   private List<Comment> comments = new ArrayList<Comment>();

   //SOME OTHER CLASS VARIABLES
   //GETTERS AND SETTERS
}
现在我知道我可以从会话中获取用户对象,并像这样为我的评论设置用户,以便能够使用JPA中的连接功能:

commentObject.setUser(TheSessionGrabedUserObject/UserObjectWhichHasFetchedFromDbUsingUserId);
但是,只要我有我的用户对象的userId,我就不需要这样做。 我正在寻找一种方法,将这个foreignKey插入到我的注释表中,而不必从会话中获取用户对象,也不必首先查询数据库来获取它


如何使用JPQL实现它?

您可以使用
entityManager.getReference()
方法。就你而言:

entityManager.getReference(User.class, userId);

这不会执行任何DB查询,但会给您一个只填充ID的
User
实例,您可以将其传递给
commentObject.setUser()

它不执行任何DB查询是什么意思,因此它如何从数据库中获取数据?我应该查询db以从数据库中获取用户,即使是代表其自身…
getReference()
不需要执行db查询来创建一个仅具有ID的实例。这就足够了,因为
commentObject
只需要用户ID。试试看。
entityManager.getReference(User.class, userId);