Search code examples
javajpafindentitymanagercomposite-key

How to find the reference when key to the find(Object.Class, {CompositeKey}) method is a composite key?


How to find a reference when we have composite key(two or more columns) to pass on as second parameter to the JPA entityManager.find(Object.class, compositeKey)?

My try- I have created an Arraylist and added the values forming compositeKey it and then passing this list to the find method.

For ex: In my situation, userid and projectid together is the key for the UserProject table and these two have been added to the arraylist named as list, which will be passed as a second parameter to the entityManager find method as shown below:

List<Integer> list = new ArrayList<Integer>();
        list.add(userProjectDO.getUserid());
        list.add(userProjectDO.getProjectid());

        UserProject userProject = em.find(UserProject.class,list);

But this always return as null, even though userid and projectId exists on the table. Has anyone been into similar issue? Solution?


Solution

  • JPA's EntityManager#find doesn't accept arrays as key but Object. Since you are talking about composite key you should implement your key in a separate class which will represent the composite key by listing all the key separate properties. You can achieve this using EmbeddedId for instance.

    For example:

    You should define the composite key class and annotate with @Embeddable:

    public class UserProjectKey implements Serializable{
        private String userId;
        private String projectId;
    
        //constructors, getters, setters
    }
    

    and use it as @EmbeddedId in your entity.

    To search by the key you can do:

    UserProjectKey key = new UserProjectKey("userIdExample", "projectIdExample");
    em.find(UserProject.class, key);