Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA lazy at simple byte[] field level

Unfortunately the code below does not work. Image is always retrieved!

@Entity
public Car implements Serializable {
    ...
    @Basic(fetch = FetchType.LAZY) //Neither with @Lob
    private byte[] image;
    ...
}

SETUP: JPA 2.0 / Hibernate 3.5 / MySQL 5.5

like image 593
CelinHC Avatar asked Oct 26 '11 11:10

CelinHC


2 Answers

Remember that the JPA provider is not required to fetch the data lazily when you specify it so. It's a hint and not a requirement.

JPA Specification 2.0 11.1.6

The EAGER strategy is a requirement on the persistence provider runtime that data must be eagerly fetched. The LAZY strategy is a hint to the persistence provider runtime that data should be fetched lazily when it is first accessed. The implementation is permitted to eagerly fetch data for which the LAZY strategy hint has been specified. In particular, lazy fetching might only be available for Basic mappings for which property-based access is used.

like image 123
Piotr Nowicki Avatar answered Oct 02 '22 11:10

Piotr Nowicki


The trick how to achive this described in this topic: http://justonjava.blogspot.it/2010/09/lazy-one-to-one-and-one-to-many.html

I've cheched it on Hibernate v.4.3.5 and JPA v.1.5.0, PostgreSQL 9.3. Worked like a charm. Example:

public class Attachment implements FieldHandled{
    @Transient
    private FieldHandler fieldHandler;
...
...
    @Lob
    @Column(name=CONTENT, nullable=false)
    @Basic(fetch = FetchType.LAZY, optional = false)
    private byte[] content;

...
...
    public byte[] getContent() {
    if(fieldHandler!=null){
        return (byte[])fieldHandler.readObject(this, "content", content);
    }
    return content;
    }

    public void setContent(byte[] content) {
    if(fieldHandler!=null){
        fieldHandler.writeObject(this, "content", this.content, content);
        return;
    }
    this.content = content;
    }

}

Note: If you are using CGLib, implement net.sf.cglib.transform.impl.InterceptFieldEnabled instead of FieldHandled, with the same approach.

like image 31
Oleksandr_DJ Avatar answered Oct 02 '22 11:10

Oleksandr_DJ