Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate JPA not inserting rows in collection table for null values

I have tried with List and Map, but I cannot figure out how to force Hibernate 3.6.4 to persist null values in those collections. This is what I've tried:

@ElementCollection(fetch=FetchType.EAGER)
@Column(columnDefinition="longtext")
private Map<Integer, String> parameterValues;

and

@ElementCollection(fetch=FetchType.EAGER)
@OrderColumn
@Lob @Column(length=65535)
private List<String> parameterValues;

If the Map or List contains a null value, Hibernate does not persist it in a row in the collection table. When the collection is retrieved from the database, it has fewer elements than when it was stored because those that are null are not restored. The List restored null values for indices between the first and last indices with non-null values, but any null values at the end of the list were left out. The Map only contained entries for non-null values.

I hope this is making sense. It seems like a bug in Hibernate to me, but I'm hoping it's something I can fix with a different configuration.

like image 472
dave_erie Avatar asked Mar 06 '13 19:03

dave_erie


1 Answers

Turns out this is a bug in Hibernate...well, not according to Gavin King, but according to many others that would like to store Nulls in the DB. See HHH-772. This issue will apparently never be resolved.

So, I had to work around it by adding an @Embeddable class for my parameter values that happily stores a null value in the DB, like this:

@Embeddable
@Access(AccessType.FIELD)
public final class ParameterValue {
    @Basic(optional=false)
    private int id;

    @Column(columnDefinition="longtext")
    private String value;

    /** For JPA */
    ParameterValue() {} 

    public ParameterValue(int id, String value) {
            this.id = id;
        this.value = value;
    }

    /**
     * @return the id
     */
    public int getId() {
            return id;
    }

    /**
     * @return the value
     */
    public String getValue() {
            return value;
    }
}
like image 197
dave_erie Avatar answered Oct 09 '22 01:10

dave_erie