Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 294
Erik Hofer Avatar asked Aug 19 '16 13:08

Erik Hofer


1 Answers

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.

like image 99
Erik Hofer Avatar answered Oct 30 '22 07:10

Erik Hofer