Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA managed mapping with different entities error

I have a form and this form need to update my record but apparently not updating and i get below error message. Dealing this exception with in 4 days and i decide to ask a question. If you need an extra information i can add some.

JSP Exception;

MergeContext#attempt to create managed -> managed mapping with different entities: [main.model.Users#1]; [main.model.Users#1]; nested exception is java.lang.IllegalStateException: MergeContext#attempt to create managed -> managed mapping with different entities: [main.model.Users#1]; [main.model.Users#1]

Java Exception;

java.lang.IllegalStateException: MergeContext#attempt to create managed -> managed mapping with different entities: [main.model.Users#1]; [main.model.Users#1]

Controller; its get Position User and Domain info from form and saves it to DB;

@PostMapping("/save-personel-info")
public String savePersonelInfo(@RequestParam int id, HttpServletRequest request, @ModelAttribute("Users") Users users, @ModelAttribute("Positions") Positions positions, @ModelAttribute("Domains") Domains domains, ModelMap model){
    usersService.save(users);
    request.setAttribute("mode", "MODE_USERS");
    return "redirect:/index";
}

Service;

@Service
@Transactional
public class UsersService {

    public void save(Users users){
        usersRepository.save(users);
    }
}

Form;

<form:form method="POST" action="/save-personel-info" modelAttribute="Users">
    <tr>
        <form:input id="1-1-0" type="hidden" class="form-control" path="id"/>
            <td><form:input id="1-1-0" type="text" class="form-control" path="username" /></td>
            <td><form:input id="1-1-0" type="text" class="form-control" path="mail" /></td>
        <td>
            <form:select path="Positions" class="form-control">
                <form:options items="${Pst}"  itemValue="id" itemLabel="position_name" />
            </form:select> 
        </td>                                   
        <td>
            <form:select path="Domains" class="form-control">
                <form:options items="${Domains}"  itemValue="id" itemLabel="domain_name" />
            </form:select> 
        </td>
    </tr>
    <input type="submit" value="Submit" />
</form:form>

User Class;

@Component
@Entity
public class Users {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;
    public String username;
    public String mail;

    @Temporal(TemporalType.DATE)
    public Date enrolment_date;

    @ManyToOne(cascade = CascadeType.ALL)
    public Domains domains;

    @ManyToOne(cascade = CascadeType.ALL)
    public Positions positions;

    @OneToMany(targetEntity = UserLanguages.class, mappedBy = "users", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    public Set<UserLanguages> userlanguages = new HashSet<UserLanguages>();

    @OneToMany(targetEntity = UserCertificates.class, mappedBy = "users", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    public Set<UserCertificates> usercertificates = new HashSet<UserCertificates>();

    @OneToMany(targetEntity = UserKnowledge.class, mappedBy = "users", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    public Set<UserKnowledge> userknowledge = new HashSet<UserKnowledge>();

What is the meaning of "managed mapping with different entities" i research the this error message but i guess no one get this error. Hibernate-orm

like image 400
debegris Avatar asked Mar 12 '17 19:03

debegris


1 Answers

This error message says that Hibernate has detected invalid 'managed entity' -> 'managed entity' mappings where key != value.

MergeContext stores mappings of managed entities to merged entities (and vice versa) and I guess that somehow you have two distinct managed entities loaded at the same time that represent the same record in the database (that's why you can get this error). (Source: internal source code of Hibernate Core analysis)

It's hard to say from the provided example where another one Users entity is. So I'm writing here a few ideas:

  • Users entity may be defined in Domains, Positions, UserLanguages, UserCertificates, or UserKnowledge classes. If you find it there with CascadeType.ALL / CascadeType.PERSIST, remove cascade property.

  • If somewhere you're using Users entities in a collection and trying to persist it, you may also encounter this error. Override equals() and hashCode() methods of Users class and use a Set to ensure object uniqueness. The equals() method may be as simple as comparing ids:

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
    
        Users that = (Users) o;
    
        return getId() == that.getId();
    }
    
    @Override
    public int hashCode() {
        return Long.valueOf(getId()).hashCode();
    }
    
  • Look carefully for other Users entities in your program and do session.evict(users) to remove the object instance from the session cache.

like image 75
naXa Avatar answered Oct 22 '22 21:10

naXa