hibernatejpacdimappingexception

Hibernate MappingException: Unknown entity: com.xxxxxx.service.model.$Proxy$_$$_WeldClientProxy


I'm using maven multimodule project. I divided my logic into different layers, Presentation, Business logic, data layer, each one in a separate module(layer). When I try to insert an object, this exception occurs:

org.hibernate.MappingException: Unknown entity: com.xxxxx.service.model.Object$Proxy$_$$_WeldClientProxy

How is this caused and how can I solve it?

I'm using CDI bean and the application is based on JSF2 and Hibernate.


Solution

  • This problem will happen when you have a JPA entity which is also declared as a CDI managed bean like below:

    @Named // Or @XxxScoped
    @Entity
    public class YourEntity {}
    

    And you attempt to persist the CDI managed bean instance itself like below:

    @Inject
    private YourEntity yourCDIManagedEntity;
    
    @PersistenceContext
    private EntityManager entityManager;
    
    public void save() {
        entityManager.persist(yourCDIManagedEntity);
    }
    

    This is not the correct way. You should not make your entity a CDI managed bean. A CDI managed bean is actually a proxy class. You can clearly see this back in your exception message. It says it doesn't know the entity com.xxxxx.service.model.Object$Proxy$_$$_WeldClientProxy instead of that it doesn't know the entity com.xxxxx.service.model.Object.

    @Entity // NO @Named nor @XxxScoped!
    public class YourEntity {}
    

    And you should prepare it as a normal entity instance and then you can safely persist it as a normal entity.

    private YourEntity yourNormalEntity;
    
    @PersistenceContext
    private EntityManager entityManager;
    
    @PostConstruct
    public void init() {
        yourNormalEntity = new YourEntity();
    }
    
    public void save() {
        entityManager.persist(yourNormalEntity);
    }