Question

Within an Entity class, can I have any object as an attribute and when I persist the Entity to the database will it also persist that objects attributes?

Was it helpful?

Solution

If the object is serializable, you could serialize it as a BLOB. But that's not something you want to do because

  • it would be inefficient to constantly serialize and deserialize the object
  • it would be very fragile: a change in the object class would make it impossible (or hard if you know what you're doing) to read previous versions already saved in the database
  • only Java could make sense of the blob
  • you could not do any query on this object

So, basically, the answer is no. JPA entities can have embedded objects, whose fields are mapped to columns, or can have associations with other entities (OneToOne, OneToMany, ManyToOne or ManyToMany).

My advice: think about the design of your database first, then map the schema to JPA entities. If you start writing an object model without even thinking how it will be persisted in the database, you won't go very far.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top