简体   繁体   中英

Difficulty creating relationship with abstract class and embedded attribute with JPA/Hibernate

I'm trying, but have not been successful so far, using the following classes with Hibernate.

@MappedSuperclass
@Embeddable
    public abstract class Foo {
        //  atributes...
    }

@Embeddable
    public class Poo extends Foo {
        // atributes...
    }

@Entity  
@Table
public class None {

    // atributes...

    @Embedded
    private Foo foo;

    // constructor
    public None(Foo foo) {
        this.foo = foo;
        }
    }

 // example of save
None none = new None(Poo poo);    

save(none);

Hibernate returns: Cannot instantiate abstract class or interface

Is it possible to perform this operation with JPA?

I ran into the same problem.

It seems like @embedable does not work with @DiscriminatorColumn . The only way I could get this to work is to use @DiscriminatorColumn , but treat the @embedable like a separate entity on the same table. What this means is that the query will likely join the table to itself.

@Entity
@Table(name="tbComputers")
public class Computer{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public long id;     

    public String motherboard;    

    @OneToOne
    @JoinColumn(name="id")
    public CPU cpu;    
}

@Entity
@DiscriminatorColumn(name="cpu_type")
@Table(name="tbComputers")
public abstract class CPU {

    @Id
    private Long id;

    @Column(name = "cpu")
    public String name;

    public abstract String someProcessorSpecificMethod();

}

@Entity
@DiscriminatorValue("Intel")
public class Intel extends CPU {

    @Override
    public String someProcessorSpecificMethod() {
        return "Intel";
    }

}

@Entity
@DiscriminatorValue("AMD")
public class AMD extends CPU {

    @Override
    public String someProcessorSpecificMethod() {
        return "AMD";
    }

}

EDIT: After further testing I found that while this works for reading data, it does not for persisting. It will create a separate INSERT. It seems like it is not supported https://hibernate.atlassian.net/browse/HHH-1910 . The alternative is to to split the table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM