nevster
nevster

Reputation: 6455

In JPA, how do I map a table to an entity which is a composite?

Sometimes you have a huge entity with numerous fields and it would be nice to split up the entity into separate classes to handle the complexity.

Say I have a table Foo with columns

someStuff, aThingBlah, aThingEtc, bThingWhatever, bThingBacon

and this class (annotations left out)

class Foo {
  String someStuff;
  String aThingBlah;
  String aThingEtc;
  String bThingWhatever;
  String bThingBacon;
}

I'd like to refactor this (without changing the db table) to

class Foo {
  String someStuff;
  AThing aThing;
  BThing bThing;
}
class AThing {
  String blah;
  String etc;
}
class BThing {
  String whatever;
  String bacon;
}

Is it possible to do this and how?

Upvotes: 1

Views: 123

Answers (2)

kem
kem

Reputation: 1127

Here's the basics...

class Foo {

  String someStuff;

  @Embedded
  @AttributeOverrides({
     @AttributeOverride( name = "blah", column = @Column(name="aThingBlah") ),
     ...
  })
  AThing aThing;

};

@Embeddable
class AThing {

  @Column(...)
  String blah;

}

Upvotes: 1

Shaun Stone
Shaun Stone

Reputation: 626

I dont think it is possible. which one holds the id? sounds like they would all share the same id and because of that hibernate would not know how to load or save any of these. (without some sort of discriminator)

also If i were to save a BThing then what would happen to the fields defined in Foo,*Athing*? They would be totally out of hibernates scope.

Upvotes: 0

Related Questions