开发者

Hibernate Component with Generics

开发者 https://www.devze.com 2022-12-12 16:57 出处:网络
Ok, this question is best explained in code. So will try to present the most succinct example I can. Timestamped.java

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 mak开发者_Python百科ing Foo abstract and moving the value field to each of the subclasses with additional annotations.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消