0
votes

I have two entity 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 :

@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:

commentObject.setUser(TheSessionGrabedUserObject/UserObjectWhichHasFetchedFromDbUsingUserId);

but as long as I have the userId for my user Object I do not need to do this. 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 !

how I'm gonna do it using JPQL ?

1

1 Answers

0
votes

You can use the entityManager.getReference() method. 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().