java – Criteria. DISTINCT_ ROOT_ Entity does not block duplicate objects
I have the following Dharma:
@Override public List<AdminRole> findAll() { Session session = sessionFactory.getCurrentSession(); Criteria criteria = session.createCriteria(AdminRole.class); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return criteria.list(); }
Actually, I want to retrieve all entries from the database
Sometimes I see repetition This happens when I add users with adminrole
I've seen that it's possible. When I use eager to extract types, it should be repaired by adding the following lines:
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
But that doesn't help me
My mapping:
@Entity @Table(name = "terminal_admin_role") public class AdminRole { @Id @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 @Override public String toString(){ return role; } @Override 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; } @Override public int hashCode() { return role.hashCode(); } }
and
@Entity @Table(name = "terminal_admin") public class TerminalAdmin { @ManyToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL) @JoinTable(name = "admin_role",joinColumns = { @JoinColumn(name = "admin_id",nullable = false) },inverseJoinColumns = { @JoinColumn(name = "role_id",nullable = false) }) private Set<AdminRole> adminRoles; //... }
Attached:
I cannot switch the extraction type
I don't want to put this list together
Solution
There is no reason to use distinct_ ROOT_ Entity or anything similar, what you need is:
session.createCriteria(AdminRole.class).list();
If you repeat, then you really have a database Check the code that saves adminroles directly or cascade from other entities
When cascading persist / merge operations from other entities, ensure that the operations cascade to persistent / detached adminrole instances instead of temporary (New) instances