JPA - Eager - Lazy Best Practice

JBoss EAP 6
Hibernate 4

I have a J2EE application with a web browser client. (Apache click) Both internal business logic and the client use the same object objects.

I would like to have all the relationships in objects set to lazy loading. So I have good performance.

But when using entities on the client (this is server-side code for the Apache click) I need many relationships to be loaded. Client code accesses the server through a bean session.

So, I have several ways to solve this problem:

  • Create 2 from each JPA object, one with eager loading and one with lazy loading. And then use one that eagerly loads in the client, and one that has lazy loading on the server. Most of the server logic will be in a transaction, so lazy loading is great here.

  • Make all relationships lazy loading. When accessing objects from the client, make sure that there is a transaction. (@TransactionAttribute (TransactionAttributeType.REQUIRED)) and encode access to the required fields so that they are available after the bean session. But this means that I have to start the transaction when it is not required, i.e. If I get only some objects. And I have to support more code. And I must know exactly what kind of relationship the client needs.

  • , -, 2 , - lazy, , . :

    @MappedSuperclass
    public class SuperOrder {

    @Id
    @Column(name = "id")
    @GeneratedValue(.....)
    private Long id;

    @Column(name = "invoice", length = 100)
    private String invoice;

1

    @Entity
    @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    @Table(name = "testorder")
    @SequenceGenerator(....)
    public class Order extends SuperOrder {

    @ManyToOne(targetEntity = PrintCustomerEnt.class, fetch = FetchType.EAGER, optional = true)
    @JoinColumn(name = "print_customer_id", nullable = true)
    @ForeignKey(name = "fk_print_customer")
    @Valid
    private PrintCustomerEnt printCustomer;

    public PrintCustomerEnt getPrintCustomer() {
        return printCustomer;
    }

    public void setPrintCustomer(final PrintCustomerEnt printCustomer) {
        this.printCustomer = printCustomer;
    }

    }

2

    @Entity
    @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    @Table(name = "testorder")
    @SequenceGenerator(...)
    public class LazyOrder extends SuperOrder {

    @Transient
    private String printCustomerName;

    @Column(name = "print_customer_id", nullable = true)
    private Long printCustomerId;

... - .

, . , .

+3
2

JPA , , , JPQL (HQL) - FETCH. - JPA .

+1

JPA 2, , , :

  • LAZY Inicialization OneToMany, ManyToMany Relations.
  • EAGER Inicalization OneToOne, ManyToOne Relations.

99% . , - , .

. , JOIN FETCH Lazy Inicialization, Prefetch. :

@Entity
class Entity{
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Basic(optional = false)
  private Integer id;

  @OneToMany(cascade = CascadeType.ALL, mappedBy = "mappedName",
        orphanRemoval = true)
  private List<Child1> collection1;

  @OneToMany(cascade = CascadeType.ALL, mappedBy = "mappedName",
        orphanRemoval = true)
  private List<Child2> collection2;  }

:

class EntityController{

  public Entity findCompraFolioFull(Integer id) {
    EntityManager em = getEntityManager();
    try {
        Entity entity =  em.find(Entity.class, id);
        //Initialize Collections inside Transaccion, this prevents
        //LazyInizialization No Proxy Exception later in code when calling
        //hollow collections
        cp.getCollection().size();
        cp.getCollection().size();
        return cp;
    } finally {
        em.close();
    }
  } 
}

FETCH JOIN

 public Entity findEntityByJoinFetch(Integer id) {
    EntityManager em = getEntityManager();
    try {
        TypedQuery<Entity> tq = em.createQuery(
                "SELECT e FROM Entity e\n"
                        + "LEFT JOIN FETCH e.collection1\n"
                        + "LEFT JOIN FETCH  e.collection2\n"
                        + "WHERE e.id = :id", Entity.class);
        tq.setParameter("id", id); 
        return tq.getSingleResult();
    } finally {
        em.close();
    }
}

, Fetch Join Appoach:

  • java.util.List, getSingleResult() - MultipleBags OneToMany Relation.

  • java.util.set, , , HashCode() , @Override , JViewAFX TableView , . Item TableView, .

+1

All Articles