Vivek V K
Vivek V K

Reputation: 1148

Persist members of an object that an entity "has" rather than the object itself

As a minimal example, if I have 2 classes like this:

    /* A is an entity while B is not. C is another class irrelevant 
for this problem. */
        class B{
             Integer bval1;
             Double bval2;
        }

        @Entity
        class A extends C {
             @Id
             @GeneratedValue(strategy= GenerationType.AUTO)
             Integer aid;
             @column
             Double aval1;
             @???
             B b;

        }

What do I fill at "???" (or somewhere else ) so that it gets persisted in a table with the structure as:

aid | aval1 | bval1 | bval2

Is this possible or should I restructure my classes?

Upvotes: 1

Views: 64

Answers (3)

Neil Stockton
Neil Stockton

Reputation: 11531

You make class B @Embeddable. That is what embeddable is for.

One JPA provider (DataNucleus) allows specification ofsomethig similar to a JPA AttributeConverter that converts the B to multiple columns (the standard AttributeConverter only converts to one column) so, if using that, you could avoid putting @Embeddable on your B class. That is clearly a vendor extension though, so non-portable if that is important to you.

Other than that, the answer is no you cannot do what you want.

Upvotes: 1

Sonu Chauhan
Sonu Chauhan

Reputation: 7

You can't replace @??? with anything because your pojo has only one primary key. And obviously there is no solution for your question.

Upvotes: -1

Alex Minjun Yu
Alex Minjun Yu

Reputation: 3707

To directly answer your question.
There is nothing you can fill in the ??? ONLY to achieve what you want.

If you can make Class B a @MappedSuperclass without making it a @Entity and make A extend B, you can achieve your goal. Note that you also need to make the attributes in Class B @Column.

This way B is not an @Entity and class A does not need to include the attributes in B, whew...

update:

Per comments with OP and updated question, I am afraid the answer would just be that it is impossible to do so.

Upvotes: 1

Related Questions