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





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















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?










share|improve this question





























    0















    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?










    share|improve this question

























      0












      0








      0








      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?










      share|improve this question














      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?







      java jpa find entitymanager composite-key






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 16 '18 at 13:21









      Nitesh singhNitesh singh

      51




      51
























          2 Answers
          2






          active

          oldest

          votes


















          0














          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);





          share|improve this answer

































            0














            I have found another approach i.e. writing namedQuery to search the table. Posting the implementation just in case it helps anyone.



            final Query query = em.createNamedQuery("UserProject.findByAll");


            UserProject Entity class:



            @Entity
            @Table(name = "userproject", schema = "public")

            @NamedQueries({ @NamedQuery(name = "UserProject.findByAll", query = "SELECT a FROM UserProject a where a.userid = :userid and a.projectid = :projectid"),
            @NamedQuery(name = "UserProject.findByUserId", query = "SELECT a FROM UserProject a where a.userid = :userid"),
            @NamedQuery(name = "UserProject.findById", query = "SELECT a FROM UserProject a where a.id = :id" )})
            public class UserProject implements Serializable {
            private static final long serialVersionUID = 1L;


            @Id @GeneratedValue(strategy= GenerationType.IDENTITY)
            @Column(name = "id")
            private Integer id;

            @Column(name = "userid")
            private Integer userid;

            @Column(name = "projectid")
            private Integer projectid;

            @Column(name = "created")
            private Timestamp created;

            @Column(name = "modified")
            private Timestamp modified;

            @Column(name = "modifiedbyid")
            private Integer modifiedbyid;

            @Column(name = "role")
            private String role;

            public Integer getId() {
            return id;
            }

            public void setId(final Integer id) {
            this.id = id;
            }

            public Integer getUserid() {
            return userid;
            }

            public void setUserid(final Integer userid) {
            this.userid = userid;
            }


            public void setProjectid(final Integer projectid) {
            this.projectid = projectid;
            }

            public Timestamp getCreated() {
            return created;
            }

            public void setCreated(final Timestamp created) {
            this.created = created;
            }

            public Timestamp getModified() {
            return modified;
            }

            public void setModified(final Timestamp modified) {
            this.modified = modified;
            }

            public Integer getModifiedbyid() {
            return modifiedbyid;
            }

            public void setModifiedbyid(final Integer modifiedbyid) {
            this.modifiedbyid = modifiedbyid;
            }

            public String getRole() {
            return role;
            }

            public void setRole(final String role) {
            this.role = role;
            }
            }


            And finally set the query parameters i.e. compositeKey values(userid,projectid) as :



            final Query query = em.createNamedQuery("UserProject.findByAll");
            query.setParameter("userid",userProjectDO.getUserid());
            query.setParameter("projectid",userProjectDO.getProjectid());
            List<UserProject> userProjectList = query.getResultList();


            userProjectList would contain the row which matches the compositeKey (userId,projectId)



            One advantage I see with this approach is that I can write N number of named queries inside the entity class as per the need/requirement. For ex: If we need to work on a view created out of this table. It can be easily achieved by first creating the view and then write another named query to work on it.






            share|improve this answer
























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53338755%2fhow-to-find-the-reference-when-key-to-the-findobject-class-compositekey-met%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              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);





              share|improve this answer






























                0














                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);





                share|improve this answer




























                  0












                  0








                  0







                  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);





                  share|improve this answer















                  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);






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 16 '18 at 13:34

























                  answered Nov 16 '18 at 13:28









                  NiVeRNiVeR

                  7,37341931




                  7,37341931

























                      0














                      I have found another approach i.e. writing namedQuery to search the table. Posting the implementation just in case it helps anyone.



                      final Query query = em.createNamedQuery("UserProject.findByAll");


                      UserProject Entity class:



                      @Entity
                      @Table(name = "userproject", schema = "public")

                      @NamedQueries({ @NamedQuery(name = "UserProject.findByAll", query = "SELECT a FROM UserProject a where a.userid = :userid and a.projectid = :projectid"),
                      @NamedQuery(name = "UserProject.findByUserId", query = "SELECT a FROM UserProject a where a.userid = :userid"),
                      @NamedQuery(name = "UserProject.findById", query = "SELECT a FROM UserProject a where a.id = :id" )})
                      public class UserProject implements Serializable {
                      private static final long serialVersionUID = 1L;


                      @Id @GeneratedValue(strategy= GenerationType.IDENTITY)
                      @Column(name = "id")
                      private Integer id;

                      @Column(name = "userid")
                      private Integer userid;

                      @Column(name = "projectid")
                      private Integer projectid;

                      @Column(name = "created")
                      private Timestamp created;

                      @Column(name = "modified")
                      private Timestamp modified;

                      @Column(name = "modifiedbyid")
                      private Integer modifiedbyid;

                      @Column(name = "role")
                      private String role;

                      public Integer getId() {
                      return id;
                      }

                      public void setId(final Integer id) {
                      this.id = id;
                      }

                      public Integer getUserid() {
                      return userid;
                      }

                      public void setUserid(final Integer userid) {
                      this.userid = userid;
                      }


                      public void setProjectid(final Integer projectid) {
                      this.projectid = projectid;
                      }

                      public Timestamp getCreated() {
                      return created;
                      }

                      public void setCreated(final Timestamp created) {
                      this.created = created;
                      }

                      public Timestamp getModified() {
                      return modified;
                      }

                      public void setModified(final Timestamp modified) {
                      this.modified = modified;
                      }

                      public Integer getModifiedbyid() {
                      return modifiedbyid;
                      }

                      public void setModifiedbyid(final Integer modifiedbyid) {
                      this.modifiedbyid = modifiedbyid;
                      }

                      public String getRole() {
                      return role;
                      }

                      public void setRole(final String role) {
                      this.role = role;
                      }
                      }


                      And finally set the query parameters i.e. compositeKey values(userid,projectid) as :



                      final Query query = em.createNamedQuery("UserProject.findByAll");
                      query.setParameter("userid",userProjectDO.getUserid());
                      query.setParameter("projectid",userProjectDO.getProjectid());
                      List<UserProject> userProjectList = query.getResultList();


                      userProjectList would contain the row which matches the compositeKey (userId,projectId)



                      One advantage I see with this approach is that I can write N number of named queries inside the entity class as per the need/requirement. For ex: If we need to work on a view created out of this table. It can be easily achieved by first creating the view and then write another named query to work on it.






                      share|improve this answer




























                        0














                        I have found another approach i.e. writing namedQuery to search the table. Posting the implementation just in case it helps anyone.



                        final Query query = em.createNamedQuery("UserProject.findByAll");


                        UserProject Entity class:



                        @Entity
                        @Table(name = "userproject", schema = "public")

                        @NamedQueries({ @NamedQuery(name = "UserProject.findByAll", query = "SELECT a FROM UserProject a where a.userid = :userid and a.projectid = :projectid"),
                        @NamedQuery(name = "UserProject.findByUserId", query = "SELECT a FROM UserProject a where a.userid = :userid"),
                        @NamedQuery(name = "UserProject.findById", query = "SELECT a FROM UserProject a where a.id = :id" )})
                        public class UserProject implements Serializable {
                        private static final long serialVersionUID = 1L;


                        @Id @GeneratedValue(strategy= GenerationType.IDENTITY)
                        @Column(name = "id")
                        private Integer id;

                        @Column(name = "userid")
                        private Integer userid;

                        @Column(name = "projectid")
                        private Integer projectid;

                        @Column(name = "created")
                        private Timestamp created;

                        @Column(name = "modified")
                        private Timestamp modified;

                        @Column(name = "modifiedbyid")
                        private Integer modifiedbyid;

                        @Column(name = "role")
                        private String role;

                        public Integer getId() {
                        return id;
                        }

                        public void setId(final Integer id) {
                        this.id = id;
                        }

                        public Integer getUserid() {
                        return userid;
                        }

                        public void setUserid(final Integer userid) {
                        this.userid = userid;
                        }


                        public void setProjectid(final Integer projectid) {
                        this.projectid = projectid;
                        }

                        public Timestamp getCreated() {
                        return created;
                        }

                        public void setCreated(final Timestamp created) {
                        this.created = created;
                        }

                        public Timestamp getModified() {
                        return modified;
                        }

                        public void setModified(final Timestamp modified) {
                        this.modified = modified;
                        }

                        public Integer getModifiedbyid() {
                        return modifiedbyid;
                        }

                        public void setModifiedbyid(final Integer modifiedbyid) {
                        this.modifiedbyid = modifiedbyid;
                        }

                        public String getRole() {
                        return role;
                        }

                        public void setRole(final String role) {
                        this.role = role;
                        }
                        }


                        And finally set the query parameters i.e. compositeKey values(userid,projectid) as :



                        final Query query = em.createNamedQuery("UserProject.findByAll");
                        query.setParameter("userid",userProjectDO.getUserid());
                        query.setParameter("projectid",userProjectDO.getProjectid());
                        List<UserProject> userProjectList = query.getResultList();


                        userProjectList would contain the row which matches the compositeKey (userId,projectId)



                        One advantage I see with this approach is that I can write N number of named queries inside the entity class as per the need/requirement. For ex: If we need to work on a view created out of this table. It can be easily achieved by first creating the view and then write another named query to work on it.






                        share|improve this answer


























                          0












                          0








                          0







                          I have found another approach i.e. writing namedQuery to search the table. Posting the implementation just in case it helps anyone.



                          final Query query = em.createNamedQuery("UserProject.findByAll");


                          UserProject Entity class:



                          @Entity
                          @Table(name = "userproject", schema = "public")

                          @NamedQueries({ @NamedQuery(name = "UserProject.findByAll", query = "SELECT a FROM UserProject a where a.userid = :userid and a.projectid = :projectid"),
                          @NamedQuery(name = "UserProject.findByUserId", query = "SELECT a FROM UserProject a where a.userid = :userid"),
                          @NamedQuery(name = "UserProject.findById", query = "SELECT a FROM UserProject a where a.id = :id" )})
                          public class UserProject implements Serializable {
                          private static final long serialVersionUID = 1L;


                          @Id @GeneratedValue(strategy= GenerationType.IDENTITY)
                          @Column(name = "id")
                          private Integer id;

                          @Column(name = "userid")
                          private Integer userid;

                          @Column(name = "projectid")
                          private Integer projectid;

                          @Column(name = "created")
                          private Timestamp created;

                          @Column(name = "modified")
                          private Timestamp modified;

                          @Column(name = "modifiedbyid")
                          private Integer modifiedbyid;

                          @Column(name = "role")
                          private String role;

                          public Integer getId() {
                          return id;
                          }

                          public void setId(final Integer id) {
                          this.id = id;
                          }

                          public Integer getUserid() {
                          return userid;
                          }

                          public void setUserid(final Integer userid) {
                          this.userid = userid;
                          }


                          public void setProjectid(final Integer projectid) {
                          this.projectid = projectid;
                          }

                          public Timestamp getCreated() {
                          return created;
                          }

                          public void setCreated(final Timestamp created) {
                          this.created = created;
                          }

                          public Timestamp getModified() {
                          return modified;
                          }

                          public void setModified(final Timestamp modified) {
                          this.modified = modified;
                          }

                          public Integer getModifiedbyid() {
                          return modifiedbyid;
                          }

                          public void setModifiedbyid(final Integer modifiedbyid) {
                          this.modifiedbyid = modifiedbyid;
                          }

                          public String getRole() {
                          return role;
                          }

                          public void setRole(final String role) {
                          this.role = role;
                          }
                          }


                          And finally set the query parameters i.e. compositeKey values(userid,projectid) as :



                          final Query query = em.createNamedQuery("UserProject.findByAll");
                          query.setParameter("userid",userProjectDO.getUserid());
                          query.setParameter("projectid",userProjectDO.getProjectid());
                          List<UserProject> userProjectList = query.getResultList();


                          userProjectList would contain the row which matches the compositeKey (userId,projectId)



                          One advantage I see with this approach is that I can write N number of named queries inside the entity class as per the need/requirement. For ex: If we need to work on a view created out of this table. It can be easily achieved by first creating the view and then write another named query to work on it.






                          share|improve this answer













                          I have found another approach i.e. writing namedQuery to search the table. Posting the implementation just in case it helps anyone.



                          final Query query = em.createNamedQuery("UserProject.findByAll");


                          UserProject Entity class:



                          @Entity
                          @Table(name = "userproject", schema = "public")

                          @NamedQueries({ @NamedQuery(name = "UserProject.findByAll", query = "SELECT a FROM UserProject a where a.userid = :userid and a.projectid = :projectid"),
                          @NamedQuery(name = "UserProject.findByUserId", query = "SELECT a FROM UserProject a where a.userid = :userid"),
                          @NamedQuery(name = "UserProject.findById", query = "SELECT a FROM UserProject a where a.id = :id" )})
                          public class UserProject implements Serializable {
                          private static final long serialVersionUID = 1L;


                          @Id @GeneratedValue(strategy= GenerationType.IDENTITY)
                          @Column(name = "id")
                          private Integer id;

                          @Column(name = "userid")
                          private Integer userid;

                          @Column(name = "projectid")
                          private Integer projectid;

                          @Column(name = "created")
                          private Timestamp created;

                          @Column(name = "modified")
                          private Timestamp modified;

                          @Column(name = "modifiedbyid")
                          private Integer modifiedbyid;

                          @Column(name = "role")
                          private String role;

                          public Integer getId() {
                          return id;
                          }

                          public void setId(final Integer id) {
                          this.id = id;
                          }

                          public Integer getUserid() {
                          return userid;
                          }

                          public void setUserid(final Integer userid) {
                          this.userid = userid;
                          }


                          public void setProjectid(final Integer projectid) {
                          this.projectid = projectid;
                          }

                          public Timestamp getCreated() {
                          return created;
                          }

                          public void setCreated(final Timestamp created) {
                          this.created = created;
                          }

                          public Timestamp getModified() {
                          return modified;
                          }

                          public void setModified(final Timestamp modified) {
                          this.modified = modified;
                          }

                          public Integer getModifiedbyid() {
                          return modifiedbyid;
                          }

                          public void setModifiedbyid(final Integer modifiedbyid) {
                          this.modifiedbyid = modifiedbyid;
                          }

                          public String getRole() {
                          return role;
                          }

                          public void setRole(final String role) {
                          this.role = role;
                          }
                          }


                          And finally set the query parameters i.e. compositeKey values(userid,projectid) as :



                          final Query query = em.createNamedQuery("UserProject.findByAll");
                          query.setParameter("userid",userProjectDO.getUserid());
                          query.setParameter("projectid",userProjectDO.getProjectid());
                          List<UserProject> userProjectList = query.getResultList();


                          userProjectList would contain the row which matches the compositeKey (userId,projectId)



                          One advantage I see with this approach is that I can write N number of named queries inside the entity class as per the need/requirement. For ex: If we need to work on a view created out of this table. It can be easily achieved by first creating the view and then write another named query to work on it.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 17 '18 at 0:32









                          Nitesh singhNitesh singh

                          51




                          51






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53338755%2fhow-to-find-the-reference-when-key-to-the-findobject-class-compositekey-met%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Florida Star v. B. J. F.

                              Danny Elfman

                              Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues