Duplicate items in an list attribute of hibernate entity












0















The problem which i am trying to solve is avoid duplicate items inside a list attribute in hibernate.
Consider the below domain.



public class Account
{
@OneToMany(fetch = FetchType.LAZY)
@JoinTable(name = "FI_COMPANY_ACCOUNT", joinColumns = @JoinColumn(name = "ACCOUNT_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "COMPANY_ID", referencedColumnName = "ID"))
private List<Company> companies;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "account", cascade = CascadeType.ALL, orphanRemoval = true)
private List<AccountDesc> accountDescList;
}

public class Company {}

public class AccountDesc
{
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PARENT_ID", referencedColumnName = "ID")
private Account account;
}


I use a Criteria API to fetch Account. In the query i perform fetch using left join for companies and inner join for accountDescList attribute. This help me to get both attributes in first select, and which avoid further selects.



Root<Account> root = criteriaQuery.from(Account.class);
root.fetch("companies", JoinType.LEFT);
root.fetch("accountDescList");


I know the root entity (here Account) can be repeated in the results. I can solve the issue using multiple ways like,
http://in.relation.to/2016/08/04/introducing-distinct-pass-through-query-hint/
https://howtoprogramwithjava.com/how-to-fix-duplicate-data-from-hibernate-queries/



But issue i face is the attribute companies inside the Account has also duplicate entities. This happen if we have more than one entry for accountDescList.



To solve the issue of duplicates in the attribute companies, I feel only solution is to use Set. Could you please clarify on the below questions.




  1. Is there a way other than using Set (for the attribute companies), to solve this issue.

  2. Even if i use can i instruct hibernate to use OrderedSetType (which uses LinkedHashSet). So that i can retain the order of the items as it returned from database. Unfortunately I do not have a attribute to use in OrderBy. I need the whatever default order returned by database.


Thanks in advance.










share|improve this question





























    0















    The problem which i am trying to solve is avoid duplicate items inside a list attribute in hibernate.
    Consider the below domain.



    public class Account
    {
    @OneToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "FI_COMPANY_ACCOUNT", joinColumns = @JoinColumn(name = "ACCOUNT_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "COMPANY_ID", referencedColumnName = "ID"))
    private List<Company> companies;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "account", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<AccountDesc> accountDescList;
    }

    public class Company {}

    public class AccountDesc
    {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "PARENT_ID", referencedColumnName = "ID")
    private Account account;
    }


    I use a Criteria API to fetch Account. In the query i perform fetch using left join for companies and inner join for accountDescList attribute. This help me to get both attributes in first select, and which avoid further selects.



    Root<Account> root = criteriaQuery.from(Account.class);
    root.fetch("companies", JoinType.LEFT);
    root.fetch("accountDescList");


    I know the root entity (here Account) can be repeated in the results. I can solve the issue using multiple ways like,
    http://in.relation.to/2016/08/04/introducing-distinct-pass-through-query-hint/
    https://howtoprogramwithjava.com/how-to-fix-duplicate-data-from-hibernate-queries/



    But issue i face is the attribute companies inside the Account has also duplicate entities. This happen if we have more than one entry for accountDescList.



    To solve the issue of duplicates in the attribute companies, I feel only solution is to use Set. Could you please clarify on the below questions.




    1. Is there a way other than using Set (for the attribute companies), to solve this issue.

    2. Even if i use can i instruct hibernate to use OrderedSetType (which uses LinkedHashSet). So that i can retain the order of the items as it returned from database. Unfortunately I do not have a attribute to use in OrderBy. I need the whatever default order returned by database.


    Thanks in advance.










    share|improve this question



























      0












      0








      0








      The problem which i am trying to solve is avoid duplicate items inside a list attribute in hibernate.
      Consider the below domain.



      public class Account
      {
      @OneToMany(fetch = FetchType.LAZY)
      @JoinTable(name = "FI_COMPANY_ACCOUNT", joinColumns = @JoinColumn(name = "ACCOUNT_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "COMPANY_ID", referencedColumnName = "ID"))
      private List<Company> companies;

      @OneToMany(fetch = FetchType.LAZY, mappedBy = "account", cascade = CascadeType.ALL, orphanRemoval = true)
      private List<AccountDesc> accountDescList;
      }

      public class Company {}

      public class AccountDesc
      {
      @ManyToOne(fetch = FetchType.LAZY)
      @JoinColumn(name = "PARENT_ID", referencedColumnName = "ID")
      private Account account;
      }


      I use a Criteria API to fetch Account. In the query i perform fetch using left join for companies and inner join for accountDescList attribute. This help me to get both attributes in first select, and which avoid further selects.



      Root<Account> root = criteriaQuery.from(Account.class);
      root.fetch("companies", JoinType.LEFT);
      root.fetch("accountDescList");


      I know the root entity (here Account) can be repeated in the results. I can solve the issue using multiple ways like,
      http://in.relation.to/2016/08/04/introducing-distinct-pass-through-query-hint/
      https://howtoprogramwithjava.com/how-to-fix-duplicate-data-from-hibernate-queries/



      But issue i face is the attribute companies inside the Account has also duplicate entities. This happen if we have more than one entry for accountDescList.



      To solve the issue of duplicates in the attribute companies, I feel only solution is to use Set. Could you please clarify on the below questions.




      1. Is there a way other than using Set (for the attribute companies), to solve this issue.

      2. Even if i use can i instruct hibernate to use OrderedSetType (which uses LinkedHashSet). So that i can retain the order of the items as it returned from database. Unfortunately I do not have a attribute to use in OrderBy. I need the whatever default order returned by database.


      Thanks in advance.










      share|improve this question
















      The problem which i am trying to solve is avoid duplicate items inside a list attribute in hibernate.
      Consider the below domain.



      public class Account
      {
      @OneToMany(fetch = FetchType.LAZY)
      @JoinTable(name = "FI_COMPANY_ACCOUNT", joinColumns = @JoinColumn(name = "ACCOUNT_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "COMPANY_ID", referencedColumnName = "ID"))
      private List<Company> companies;

      @OneToMany(fetch = FetchType.LAZY, mappedBy = "account", cascade = CascadeType.ALL, orphanRemoval = true)
      private List<AccountDesc> accountDescList;
      }

      public class Company {}

      public class AccountDesc
      {
      @ManyToOne(fetch = FetchType.LAZY)
      @JoinColumn(name = "PARENT_ID", referencedColumnName = "ID")
      private Account account;
      }


      I use a Criteria API to fetch Account. In the query i perform fetch using left join for companies and inner join for accountDescList attribute. This help me to get both attributes in first select, and which avoid further selects.



      Root<Account> root = criteriaQuery.from(Account.class);
      root.fetch("companies", JoinType.LEFT);
      root.fetch("accountDescList");


      I know the root entity (here Account) can be repeated in the results. I can solve the issue using multiple ways like,
      http://in.relation.to/2016/08/04/introducing-distinct-pass-through-query-hint/
      https://howtoprogramwithjava.com/how-to-fix-duplicate-data-from-hibernate-queries/



      But issue i face is the attribute companies inside the Account has also duplicate entities. This happen if we have more than one entry for accountDescList.



      To solve the issue of duplicates in the attribute companies, I feel only solution is to use Set. Could you please clarify on the below questions.




      1. Is there a way other than using Set (for the attribute companies), to solve this issue.

      2. Even if i use can i instruct hibernate to use OrderedSetType (which uses LinkedHashSet). So that i can retain the order of the items as it returned from database. Unfortunately I do not have a attribute to use in OrderBy. I need the whatever default order returned by database.


      Thanks in advance.







      java hibernate jpa






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 10 '18 at 4:36







      Sanush Chacko

















      asked Nov 24 '18 at 1:37









      Sanush ChackoSanush Chacko

      367




      367
























          2 Answers
          2






          active

          oldest

          votes


















          1














          I think that it is much better use Set because a set doesn't allow elements duplicated, also you can overwrite equals method of Company and put it on what fields will be validated when two elements are equals.
          The other way would be in setCompanies(List companies) method you can make something logic before this.companies = companies.stream().distinct().collect(Collectors.toList()); or
          this.companies = new ArrayList<>(new HashSet(companies)) ;






          share|improve this answer































            1















            But the issue I face is the attribute companies inside the Account has also duplicate entities.




            That shouldn't happen unless you have duplicate Company entities assigned to the same account.



            As explained in this article, using DISTINCT in the Criteria API query will remove root duplicates. However, in your case, it's not worth using JOIN FETCH on both @OneToMany relations since this will cause a Cartesian Product.



            You should fetch at most one collection at a time, and maybe use @Subselect fetching for the second collection.






            share|improve this answer
























            • Thanks Vlad for your reply. I checked and confirmed that duplicate Company entities are not assigned to the same account. I really understand the root entity is duplicated and fine with its solution. But the duplicate items in attribute (Company) is really bothering me :-) . So even if i use two fetch in one query, is it right to get items in the inner attribute duplicated?. If that is the case I will go with Set.

              – Sanush Chacko
              Nov 28 '18 at 6:51











            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%2f53454460%2fduplicate-items-in-an-list-attribute-of-hibernate-entity%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









            1














            I think that it is much better use Set because a set doesn't allow elements duplicated, also you can overwrite equals method of Company and put it on what fields will be validated when two elements are equals.
            The other way would be in setCompanies(List companies) method you can make something logic before this.companies = companies.stream().distinct().collect(Collectors.toList()); or
            this.companies = new ArrayList<>(new HashSet(companies)) ;






            share|improve this answer




























              1














              I think that it is much better use Set because a set doesn't allow elements duplicated, also you can overwrite equals method of Company and put it on what fields will be validated when two elements are equals.
              The other way would be in setCompanies(List companies) method you can make something logic before this.companies = companies.stream().distinct().collect(Collectors.toList()); or
              this.companies = new ArrayList<>(new HashSet(companies)) ;






              share|improve this answer


























                1












                1








                1







                I think that it is much better use Set because a set doesn't allow elements duplicated, also you can overwrite equals method of Company and put it on what fields will be validated when two elements are equals.
                The other way would be in setCompanies(List companies) method you can make something logic before this.companies = companies.stream().distinct().collect(Collectors.toList()); or
                this.companies = new ArrayList<>(new HashSet(companies)) ;






                share|improve this answer













                I think that it is much better use Set because a set doesn't allow elements duplicated, also you can overwrite equals method of Company and put it on what fields will be validated when two elements are equals.
                The other way would be in setCompanies(List companies) method you can make something logic before this.companies = companies.stream().distinct().collect(Collectors.toList()); or
                this.companies = new ArrayList<>(new HashSet(companies)) ;







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 24 '18 at 5:09









                Jonathan JohxJonathan Johx

                1,7761317




                1,7761317

























                    1















                    But the issue I face is the attribute companies inside the Account has also duplicate entities.




                    That shouldn't happen unless you have duplicate Company entities assigned to the same account.



                    As explained in this article, using DISTINCT in the Criteria API query will remove root duplicates. However, in your case, it's not worth using JOIN FETCH on both @OneToMany relations since this will cause a Cartesian Product.



                    You should fetch at most one collection at a time, and maybe use @Subselect fetching for the second collection.






                    share|improve this answer
























                    • Thanks Vlad for your reply. I checked and confirmed that duplicate Company entities are not assigned to the same account. I really understand the root entity is duplicated and fine with its solution. But the duplicate items in attribute (Company) is really bothering me :-) . So even if i use two fetch in one query, is it right to get items in the inner attribute duplicated?. If that is the case I will go with Set.

                      – Sanush Chacko
                      Nov 28 '18 at 6:51
















                    1















                    But the issue I face is the attribute companies inside the Account has also duplicate entities.




                    That shouldn't happen unless you have duplicate Company entities assigned to the same account.



                    As explained in this article, using DISTINCT in the Criteria API query will remove root duplicates. However, in your case, it's not worth using JOIN FETCH on both @OneToMany relations since this will cause a Cartesian Product.



                    You should fetch at most one collection at a time, and maybe use @Subselect fetching for the second collection.






                    share|improve this answer
























                    • Thanks Vlad for your reply. I checked and confirmed that duplicate Company entities are not assigned to the same account. I really understand the root entity is duplicated and fine with its solution. But the duplicate items in attribute (Company) is really bothering me :-) . So even if i use two fetch in one query, is it right to get items in the inner attribute duplicated?. If that is the case I will go with Set.

                      – Sanush Chacko
                      Nov 28 '18 at 6:51














                    1












                    1








                    1








                    But the issue I face is the attribute companies inside the Account has also duplicate entities.




                    That shouldn't happen unless you have duplicate Company entities assigned to the same account.



                    As explained in this article, using DISTINCT in the Criteria API query will remove root duplicates. However, in your case, it's not worth using JOIN FETCH on both @OneToMany relations since this will cause a Cartesian Product.



                    You should fetch at most one collection at a time, and maybe use @Subselect fetching for the second collection.






                    share|improve this answer














                    But the issue I face is the attribute companies inside the Account has also duplicate entities.




                    That shouldn't happen unless you have duplicate Company entities assigned to the same account.



                    As explained in this article, using DISTINCT in the Criteria API query will remove root duplicates. However, in your case, it's not worth using JOIN FETCH on both @OneToMany relations since this will cause a Cartesian Product.



                    You should fetch at most one collection at a time, and maybe use @Subselect fetching for the second collection.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 26 '18 at 5:40









                    Vlad MihalceaVlad Mihalcea

                    58.2k13163464




                    58.2k13163464













                    • Thanks Vlad for your reply. I checked and confirmed that duplicate Company entities are not assigned to the same account. I really understand the root entity is duplicated and fine with its solution. But the duplicate items in attribute (Company) is really bothering me :-) . So even if i use two fetch in one query, is it right to get items in the inner attribute duplicated?. If that is the case I will go with Set.

                      – Sanush Chacko
                      Nov 28 '18 at 6:51



















                    • Thanks Vlad for your reply. I checked and confirmed that duplicate Company entities are not assigned to the same account. I really understand the root entity is duplicated and fine with its solution. But the duplicate items in attribute (Company) is really bothering me :-) . So even if i use two fetch in one query, is it right to get items in the inner attribute duplicated?. If that is the case I will go with Set.

                      – Sanush Chacko
                      Nov 28 '18 at 6:51

















                    Thanks Vlad for your reply. I checked and confirmed that duplicate Company entities are not assigned to the same account. I really understand the root entity is duplicated and fine with its solution. But the duplicate items in attribute (Company) is really bothering me :-) . So even if i use two fetch in one query, is it right to get items in the inner attribute duplicated?. If that is the case I will go with Set.

                    – Sanush Chacko
                    Nov 28 '18 at 6:51





                    Thanks Vlad for your reply. I checked and confirmed that duplicate Company entities are not assigned to the same account. I really understand the root entity is duplicated and fine with its solution. But the duplicate items in attribute (Company) is really bothering me :-) . So even if i use two fetch in one query, is it right to get items in the inner attribute duplicated?. If that is the case I will go with Set.

                    – Sanush Chacko
                    Nov 28 '18 at 6: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%2f53454460%2fduplicate-items-in-an-list-attribute-of-hibernate-entity%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

                    Create new schema in PostgreSQL using DBeaver

                    Deepest pit of an array with Javascript: test on Codility

                    Costa Masnaga