Lob returns null using game frame and Ebean and H2

I am developing a program with game 2.3 (with Ebean and H2) for java. I have a model like this:

@Entity
public class DeviceModel extends Model implements PathBindable<DeviceModel> {

@Id
public Long id;


@Lob
@Basic(fetch=FetchType.LAZY)
public byte[] picture;

...

      

In my controller, I have a function that writes the image as byte[]

inside an object DeviceModel

and calls the function update()

. so now the image should be saved in the database.

And I have this function to show the image:

public static Result picture(Long id) {
    final DeviceModel deviceModel = DeviceModel.findByID(id);
    if (deviceModel == null){
        return notFound();
    }
    return ok(deviceModel.picture);
}

      

The funny thing deviceModel.picture

is null!

but in my opinion i have this:

        @if(deviceModel.picture != null) {
                show the picture!
        } else{
            do something else
        }

      

but it is deviceModel.picture

not null here !!! and MOST TIME the picture will be shown correctly!

I uninstalled @Basic(fetch=FetchType.LAZY)

but that didn't fix the problem.

Any idea why this is so?

+3


source to share


2 answers


I found work around this problem, but I still like to know the reason why directly accessing the image field returns null.

here is the work: I just made the field picture

private, and made the getter and setter myself. now in my controller with getPicture()

i always get data



@Entity
public class DeviceModel extends Model implements PathBindable<DeviceModel> {

@Id
public Long id;


@Lob
@Basic(fetch=FetchType.LAZY)
private byte[] picture;


public byte[] getPicture() {
    return picture;
}

public void setPicture(byte[] picture) {
    this.picture = picture;
}

...

      

+2


source


The reason for this behavior is FetchType.LAZY

(which appears to be the default for Lobs as well). It tells Ebean to fetch data lazily, i.e. Not immediately when you load the object, but only when you actually access it.

Since Ebean cannot detect access, when you go straight to field ( picture

), no loading occurs at all and you get null

.



Using getPicture()

Ebean leveraged code, it knows how to load data before returning a value.

You can overcome this behavior simply by usingFetchType.EAGER

. But you should only do this if you are sure that you always need the data, because it takes more time and memory (for example, in your example, if you have 100 photos and you want to show a list of names, it will not be necessary to upload all actual image data.

0


source







All Articles