Steve Skrla
Steve Skrla

Reputation: 1720

Hibernate Component with Generics

Ok, this question is best explained in code. So will try to present the most succinct example I can.

Timestamped.java

@Embeddable
public class Timestamped<E> {
    private E value;
    private Date timestamp;
    ...
}

Foo.java

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="TYPE")
public class Foo {
    @Embedded
    @AttributeOverides({
        @AttributeOverride(name="timestamp", column=@Column("VALUE_TS")),
        @AttributeOverride(name="value",     column=@Column("VALUE"))
    })
    private TimestampedValue<E> value;
    ...
}

Bar.java

@Entity
@DiscriminatorValue("BAR")
public class Bar extends Foo<Double> { }

What I need is for Bar to use the appropriate type converter for value.value and a different converter for each subclass of Foo. Ideally I would just like to augment this code, but I would be OK making Foo abstract and moving the value field to each of the subclasses with additional annotations.

Upvotes: 3

Views: 1391

Answers (3)

Nathan Feger
Nathan Feger

Reputation: 19496

You are running into an erasure problem. Hibernate cannot know what to do with the generic types, because that information is not available at runtime. It would be nice though.

Upvotes: 0

Jherico
Jherico

Reputation: 29240

If what you're trying to do is make many classes that correspond to many tables but use the same column names for the 'timestamp' and 'value' properties, then what you want is a 'mapped superclass' with those columns, not an embedded class. Research the @MappedSuperclass annotation.

Upvotes: 0

ChssPly76
ChssPly76

Reputation: 100706

The first approach is not going to work - you can't persist "genericized" classes.

You will either have to move value into concrete subclasses like you've suggested OR write a UserType to persist your Timestamped component.

Upvotes: 1

Related Questions