简体   繁体   English

JPQL特殊查询

[英]JPQL Special Query

I have two entity bean : 我有两个实体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
}

and my Comment class is like this : 我的Comment类是这样的:

@Entity
public class Comment {
   @Id
   @GeneratedValue
   private Long id;

   private String title;
   private String content;

   @ManyToOne
   private User user

   //SOME OTHER CLASS VARIABLES
   //GETTERS AND SETTERS
}

now I know that I can get the User Object from session and set the user for my comment like this in order to be able to use the join feature in JPA: 现在,我知道我可以从会话中获取用户对象,并为用户设置我的注释,以便能够使用JPA中的加入功能:

commentObject.setUser(TheSessionGrabedUserObject/UserObjectWhichHasFetchedFromDbUsingUserId);

but as long as I have the userId for my user Object I do not need to do this. 但是只要我有我的用户对象的userId,我就不需要这样做。 I'm looking for a way to insert this foreignKey into my comment table without getting the User Object from session or maybe query to database to fetch it first ! 我正在寻找一种方法,可以将此ForeignKey插入到我的注释表中,而无需从会话中获取User Object或查询数据库以先获取它!

how I'm gonna do it using JPQL ? 我要如何使用JPQL做到这一点?

You can use the entityManager.getReference() method. 您可以使用entityManager.getReference()方法。 In your case: 在您的情况下:

entityManager.getReference(User.class, userId);

This will not perform any DB query, but will give you a User instance with only the ID populated, and you can pass that to commentObject.setUser() . 这将不会执行任何数据库查询,但会为您提供一个User实例,其中仅填充ID,您可以将其传递给commentObject.setUser()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM