繁体   English   中英

休眠条件,分组/选择父母的不同孩子

[英]Hibernate Criteria, group/select distinct children of a parent

我有一个模型Parent,其中有一个孩子列表(列表

class Parent {
   @OneToMany(targetEntity = Child.class, cascade = CascadeType.ALL, mappedBy = "parent")
   @JsonManagedReference
   private List<Child> tags =  new ArrayList<>();

   @Column(name = "name")
   public String name;

}

class Child {
     @Column(name = "name")
     public String name;

     @ManyToOne(fetch = FetchType.LAZY)
     @JoinColumn(name = "parent_id", nullable = true)
     @JsonBackReference
     private Parent parent;
}

我在EAGER模式下选择带有孩子的父母列表(List <Parent>)。

现在,孩子们可以有相同的名字,但是我不希望同名的孩子在列表中出现多次。 有什么建议可以让集合中的同名孩子只有一次?

这是使用set删除重复值的示例代码。 如果firstName存在,则忽略第二个条目。 您可以根据需要进行修改。

但是,尽管这是您所提出问题的答案,请注意,这里有代码味道。 他们认为您必须在代码中执行此操作,而数据库允许这样做是有问题的,并且几乎可以保证存在设计缺陷。

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Test
{
    private String firstName;
    private String lastName;


    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((firstName == null) ? 0 : firstName.hashCode());
        return result;
    }


    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Test other = (Test) obj;
        if (firstName == null) {
            if (other.firstName != null)
                return false;
        } else if (!firstName.equals(other.firstName))
            return false;
        return true;
    }


    public Test(String firstName, String lastName) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
    }


    public static void main(String[] args)
    {
        List<Test> aList = new ArrayList<Test>();
        Test test1 = new Test("Tom","Hardy");
        Test test2 = new Test("Tom","Cruise");
        Test test3 = new Test("Any","Body");
        aList.add(test1);
        aList.add(test2);
        aList.add(test3);

        System.out.println("List values:");
        for (Test test : aList)
        {
            System.out.println(test.firstName + "-"+ test.lastName);
        }
        Set<Test> alphaSet = new HashSet<Test>(aList);
        System.out.println("Set values:");
        for (Test test : alphaSet)
        {
            System.out.println(test.firstName + "-"+ test.lastName);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM