Hibernate Large Class Breakdown

I have a Hibernate class which is essentially a wrapper around multiple collections.

So the class (massively simplified / pseudo) is something like:

@Entity  
public class MyClass {

  @OneToMany  
  Map1

  @OneToMany  
  Map2

  @OneToMany   
  Map3

  AddToMap1 ();  
  AddToMap2 ();  
  AddToMap3 ();  
  RemoveFromMap1 ();  
  RemoveFromMap2 ();  
  RemoveFromMap3 ();  
  DoWhateverWithMap1 ();  
  DoWhateverWithMap2 ();  
  DoWhateverWithMap3 ();  

}

etc .. Each of these cards has several methods associated with it (add / remove / interrogate / etc).

As you can imagine, by the time I added the 10th collection or so, the class was getting a bit ridiculous in size.

What I would like to do is something like:

 
@Entity  
public class MyClass {

  ClassWrappingMap1;

  ClassWrappingMap2;

  ClassWrappingMap3;
}

, :

public class ClassWrappingMap1 {

  @OneToMany
  Map

  AddToMap();  
  RemoveFromMap();  
  DoWhateverWithMap();  

}

, , , @Embedded , , , (Hibernate wrapperClass).

- - - ? ?

,
Ned

+3
2

:

EJB3, Hibernate Annotations ( @* ToOne @* ToMany). , @AssociationOverride.

, .


, .. .

- :

  • - (MyClass)
@Entity  
public class MyClass {

  @Embedded
  ClassWrappingMap1 map1;
}
@Embeddable
public class ClassWrappingMap1 {

  @OneToMany
  Map map1;

}

, ClassWrappingMap1 @Embeddable. , , @Embeddable , @Embedded.

, ClassWrappingMap . ClassWrappingMap ( @Id @EmbeddedId).

+2

-, Hibernate Interceptor , onLoad. -

public class WrapperInterceptor extends EmptyInterceptor {

    private Session session;

    public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
        if (entity instanceof MyClass) {
             MyClass myClass = (MyClass) entity;

             Query query = session.createQuery(<QUERY_TO_RETRIEVE_WRAPPED_ENTITY_GOES_HERE>);

             WrappedEntity wrappedEntity = query.list().get(0);

             myClass.setWrapperClass(new WrapperClass(wrappedEntity));
        }
    }

    public void setSession(Session session) {
        this.session = session;
    }
}

:

, , Session

, :

WrapperInterceptor interceptor = new WrapperInterceptor();

Session session = sessionFactory().openSession(interceptor);

Transaction tx = session.beginTransaction();

interceptor.setSession(session);

MyClass myClass = (MyClass) session.get(newItem, myClassId); // Triggers onLoad event

tx.commit();
session.close();

Spring AOP . . Spring Hibernate

, .

,

0

Source: https://habr.com/ru/post/1725471/


All Articles