22

I have an old table that I'm working with, which looks like this:

+------------------+--------------+------+-----+---------+-------+
| Field            | Type         | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+-------+
| BINARY_DATA_ID   | varchar(255) | NO   | PRI |         |       |
| BINARY_DATA      | longblob     | YES  |     | NULL    |       |
| BINARY_DATA_NAME | varchar(255) | YES  |     | NULL    |       |
+------------------+--------------+------+-----+---------+-------+

The main problem with this is that the BinaryData Java class loads the BINARY_DATA column, even if I only require the BINARY_DATA_NAME. I know that the best way to architect this is to split the data from the meta-data (like the file name) so they live in separate tables. From there it's trivial to make the data lazy-loaded. This is how it should have been done in the first place.

Unfortunately it may not be possible for me to do the above due to organizational constraints. As a workaround, is it possible to make that column lazy-loaded using some annotations instead of splitting things out into separate tables? I've modified the BinaryData class so that it has an inner static BinaryDataData class which is @Embedded and the attribute is @Basic(fetch=FetchType.LAZY):

@Entity
@Table
@Proxy(lazy=false)
@Inheritance(strategy=InheritanceType.JOINED)
public class BinaryData implements Serializable, Persistable<BinaryData>, Cloneable {

    private static final long serialVersionUID = /** blah */;

    @Id @Column @GeneratedValue(generator="uuid") @GenericGenerator(name="uuid", strategy="uuid")
    private String id;

    @Column
    private String binaryDataName;

    @Embedded
    @Basic(fetch = FetchType.LAZY)
    private BinaryDataData binaryData;

    @Transient
    private String cacheId;

    /**
     * Hibernate constructor
     */
    public BinaryData() { /* Creates a new instance of Attachment. */}

    public BinaryData(byte[] binaryData, String binaryDataName) {
        this.binaryData = new BinaryDataData(ArrayUtils.clone(binaryData));
        this.binaryDataName = binaryDataName;
    }

    /**
     * Returns the BinaryData byte stream.
     *
     * @return binaryData byte stream
     */
    @Embedded
    @Basic(fetch = FetchType.LAZY)
    public byte[] getBinaryData() {
        if (this.binaryData == null) {
            return new byte[0];
        }
        return binaryData.getActualData();
    }

    @Embeddable
    public static class BinaryDataData implements Serializable {
        @Column(length=32*1024*1024, columnDefinition="longblob", name="BINARY_DATA") @Lob
        private byte[] actualData;

        public BinaryDataData() { }

        public BinaryDataData(byte[] data) {
            this.actualData = data;
        }

        public byte[] getActualData() {
            if (this.actualData == null) {
                return new byte[0];
            }
            return this.actualData;
        }

        public void setBinaryData(byte[] newData) {
            this.actualData = newData;
        }

        @Override public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (!(obj instanceof BinaryDataData)) {
                return false;
            }
            final BinaryDataData other = (BinaryDataData) obj;
            if (!Arrays.equals(actualData, other.actualData)) {
                return false;
            }
            return true;
        }
    }

    /** onwards... */

Unfortunately this doesn't work. The SQL that I'm seeing still shows a complete fetch of the object even if the binary data isn't requested:

select ideaattach0_.BINARY_DATA_ID as BINARY1_9_, ideaattach0_1_.BINARY_DATA as BINARY2_9_, ideaattach0_1_.BINARY_DATA_NAME as BINARY3_9_, ideaattach0_.IDEA_BUCKET_ID as IDEA2_136_ from IDEA_ATTACHMENT ideaattach0_ inner join BINARY_DATA ideaattach0_1_ on ideaattach0_.BINARY_DATA_ID=ideaattach0_1_.BINARY_DATA_ID where ideaattach0_.BINARY_DATA_ID=?

Any ideas? Thank you.

1
  • 1
    Create a 'view' object by selecting only those required columns. Did you try that? Commented Oct 21, 2012 at 19:47

3 Answers 3

15

From Hibernate, Chapter 19. Improving performance:

Lazy attribute fetching: an attribute or single valued association is fetched when the instance variable is accessed. This approach requires buildtime bytecode instrumentation and is rarely necessary.

Sign up to request clarification or add additional context in comments.

5 Comments

Bummer... this is disappointing. Yet another frustrating moment in Hibernate usage. I wonder why it would ignore this by default?
That is interesting. I actually came across this today in the Pro JPA2 book and thought it useful. However now I know Hibernate does not support it! Quote: "Before you use this feature, you should be aware of a few pertinent points about lazy attribute fetching. First and foremost, the directive to lazily fetch an attribute is meant only to be a hint to the persistence provider to help the application achieve better performance. The provider is not required to respect the request because the behavior of the entity is not compromised if the provider goes ahead and loads the attribute."
Its not "not supported". As already pointed out, it just requires bytcode enhancement. Normally it requires buildtime stepo to perform the enhancement, although in container managed JPA provider cases it can be done at runtime (have a look at the hibernate.ejb.use_class_enhancer setting). And, Mike, its "ignored by default" because by default your classes are not enhanced. Enhance your classes in one of the means outlined.
@SteveEbersole it requires bytecode instrumentation, not bytecode enhancement. More info in stackoverflow.com/questions/26550866/…
The answer on that post you link to is utterly incorrect. These phrases both refer to the same idea, just one is generally used to to describe the process pre-5.0 and the other 5.0 and beyond. Both describe asking Hibernate to change (enhance, instrument) your domain model classes.
4

For maven project it's needed to add following plugin dependency into pom.xml:

<plugin>
    <groupId>org.hibernate.orm.tooling</groupId>
    <artifactId>hibernate-enhance-maven-plugin</artifactId>
    <version>${hibernate.version}</version>
    <executions>
        <execution>
            <configuration>
                <failOnError>true</failOnError>
                <enableLazyInitialization>true</enableLazyInitialization>
            </configuration>
            <goals>
                <goal>enhance</goal>
            </goals>
        </execution>
    </executions>
</plugin>

I have checked it in my project and it works, example of entity:

@Entity(name = "processing_record")
public class ProcessingRecord {

/**
 * Why uuid: https://www.clever-cloud.com/blog/engineering/2015/05/20/why-auto-increment-is-a-terrible-idea/
 */
@Id
@Column(name = "record_id")
@org.hibernate.annotations.Type(type = "pg-uuid")
private UUID id;

...

/**
 * Processing result.
 */
@Column(name = "result")
@Basic(fetch = FetchType.LAZY)
private String result;
...

For more details take a look on following article: LINK

Comments

0

I am aware of the date of this inquiry, however, I would have also attempted to use a projection value class that maps as subset of the columns, and use that projection with a specified named query which instantiates that projection value object, instead of the base object being referenced here.

I am working on a solution which uses this method so I do not currently have a full example. However, the basic idea is that you will create a JPA query which uses the "select NEW Projection_Object_Target" syntax, where the fields are directly referenced within the constructor of "Projection_Object_Target".

I.E. Use a constructor expression as follows:

SELECT NEW fully.qualified.package.name.ProjectionObject(baseObject.column_target_0,baseObject.column_target_1,...,baseObject.column_target_n) FROM BaseObjectMappedInDBTable AS baseObject

Generic example use-case:

String queryStr =
  "SELECT NEW fully.qualified.package.name.ProjectionObject(baseObject.column_target_0) " +
  "FROM BaseObjectMappedInTable AS baseObject";
TypedQuery<ProjectionObject> query =
  em.createQuery(queryStr, ProjectionObject.class);
List<ProjectionObject> results = query.getResultList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.