Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to use JPA @Embeddables with Hibernate. The entity and the embeddable both have a property named id:

@MappedSuperclass
public abstract class A {
    @Id
    @GeneratedValue
    long id;
}

@Embeddable
public class B extends A {

}

@Entity
public class C extends A {
    B b;
}

This raises a org.hibernate.MappingException: component property not found: id.

I want to avoid using @AttributeOverrides. I thus tried to set spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.DefaultComponentSafeNamingStrategy (I'm using Spring Boot). This did not have any effect (same exception). I, however, suspect that the setting is beeing ignored because specifying a non-existing class doesn't raise an exception.

The strange thing is, even with this variant

@Entity
public class C extends A {
    @Embedded
    @AttributeOverrides( {
        @AttributeOverride(name="id", column = @Column(name="b_id") ),
    } )
    B b;
}

I still get the same error.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
162 views
Welcome To Ask or Share your Answers For Others

1 Answer

The naming strategy configuration has changed. The new way as per the Spring Boot documentation is this:

spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl

Also, you must not use @Id within an @Embeddable. I thus created a seperate @MappedSuperclass for embeddables:

@MappedSuperclass
public abstract class A {
    @Id
    @GeneratedValue
    long id;
}

@MappedSuperclass
public abstract class E {
    @GeneratedValue
    long id;
}

@Embeddable
public class B extends E {

}

@Entity
public class C extends A {
    B b;
}

This way, the table C has two columns id and b_id. The downside is of course that A and E introduce some redundency. Comments regarding a DRY approach to this are very welcome.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...