Erik Hofer
Erik Hofer

Reputation: 2656

Hibernate embeddables: component property not found

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.

Upvotes: 11

Views: 17853

Answers (2)

fullstack20148
fullstack20148

Reputation: 185

This conflict can occurs when your Embeddable class has also Id column. Then try to remove Id field from class with @Embeddable.

Upvotes: 1

Erik Hofer
Erik Hofer

Reputation: 2656

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.

Upvotes: 13

Related Questions