Criteria.DISTINCT_ROOT_ENTITY doesn’t prevent duplicated objects Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Criteria.DISTINCT_ROOT_ENTITY doesn’t prevent duplicated objects without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have following dao method:

public List<AdminRole> findAll() {
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(AdminRole.class);
    return criteria.list();

Actually I want to retrieve all entries from database.

Sometimes I see duplicates. This happens when I add user with AdminRole.

I have read that it is possible when I use EAGER fetch type and this should be fix adding following line:


But this doesn’t help me.

my mapping:

@Table(name = "terminal_admin_role")
public class AdminRole {

    @Column(name = "role_id", nullable = false, unique = true)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_id")
    @SequenceGenerator(name = "user_id", sequenceName = "user_id")
    private Long adminId;

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

    public AdminRole(String role) {
        this.role = role;

    public AdminRole() {

    // get set

    public String toString(){
        return role;

    public boolean equals(Object o) {
        if (this == o) {
            return true;
        if (!(o instanceof AdminRole)) {
            return false;

        AdminRole adminRole = (AdminRole) o;

        if (!role.equals(adminRole.role)) {
            return false;

        return true;

    public int hashCode() {
        return role.hashCode();


@Table(name = "terminal_admin")
public class TerminalAdmin {
    @JoinTable(name = "admin_role", joinColumns = { 
        @JoinColumn(name = "admin_id", nullable = false) }, 
        inverseJoinColumns = { @JoinColumn(name = "role_id", 
                nullable = false) })
    private Set<AdminRole> adminRoles;      


I cannot switch fetch type.

I don’t want to put this list into set.


There is no reason to use DISTINCT_ROOT_ENTITY or anything similar, all you need is:


If you get duplicates, then you really have them in the database. Check the code which saves AdminRoles either directly or by cascading from other entities.

When cascading PERSIST/MERGE operations from other entities, make sure that the operation is cascaded to a persistent/detached AdminRole instance, not to a transient (new) one.

We are here to answer your question about Criteria.DISTINCT_ROOT_ENTITY doesn’t prevent duplicated objects - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji