jpajakarta-eeeclipselinkhibernate-ogm

@PrePersist insert query


I'm in the following scenario: I have an Entity managed via JPA in mysql. Some field of the PolyPersistclass are stored in a mysql table, a single field of that entity (PolyPersistData), which contains (pretty big) data is stored in MongoDB using a @PrePersist handler. So, PolyPersist is stored in mysql table (eclipselink), but the field PolyPersistData in MongoDB (hibernate-ogm).

@Entity
public class PolyPersist {

    public PolyPersist() {
    }
    public PolyPersistData getPolyPersistData() {
        return this.polyPersistData;
    }
    public void setPolyPersistData(PolyPersistData o) {
        this.polyPersistData = o;
    }

    @PrePersist
    @PreUpdate
    @PreMergeTransient
    public void serializeData() throws UnsupportedEncodingException, ClassNotFoundException, JAXBException {
        EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("MongoEM");
        EntityManager em = emfactory.createEntityManager();
        em.persist(this.polyPersistData);
        }

    }

}

I know it isn't a best practice "crossing" the lifecycle of those Entities (PolyPersist and PolyPersistData). Also, the instantiation of an EntityManager in that handler is a problem for sure (as far as I know I should limit EntityManager instances as they are heavy computationally/memory footprint speaking). Which is the best way to do that?


Solution

  • As you mentioned there are some problems with this implementation. Some of them are:

    I believe the best way to do that is to separate MySQL and MongoDB persistence completely in diferent DAO/Repositories and coordinate this from an upper layer or interceptor. The implementation will be diferent depending of with platform is being used (Java SE/EE/Spring).

    I guess you don't need MongoDB at all. Removing MongoDB would make the solution simpler. You could handle the entity size problem inside MySQL using a custom tablespace or another DB level trick.