Nurjan
Nurjan

Reputation: 6073

Persisting entities with references to other entity classes in JPA

I am working with JSF 2.1, Netbeans 7.0.1, Glassfish 3.1.1, JPA + EJB.

For instance, I have an entity class called User and it has reference (many-to-one relationship) with entity class UserType.

The table user_type associated with the entity UserType is already loaded with all possible user types and no data are supposed to be added to this table. The data from the table user_type is only used to choose from.

In one of the forms I ask user to choose UserType for the User being created by using h:selectOneListBox tag. In the backing bean I create new UserType object, set the chosen id to it and put UserType into the User entity class. However, all other fields in created object of UserType are null.

My question is when I persist User into the database will JPA "understand" that the UserType with such id referenced by the User entity already exists in the database and will just update (merge) the existing record and not try to create a new one. Or I have to preload the needed entity UserType from the database by its id and then put it into User and the ask JPA to update UserType?

Upvotes: 1

Views: 591

Answers (1)

Mr.J4mes
Mr.J4mes

Reputation: 9266

From the <h:selectOneListBox> component, I think you should get out only the ID of the UserType. After that, you can ask your EJB to create the relationship for you. It should look like this:

@Stateless
public class MrStatelessBean {
   public void createUser(User u, long typeID) {
      UserType type = em.find(UserType.class, typeID);
      u.setUserType(type);
      em.persist(u);
   }
}  

Upvotes: 1

Related Questions