sangfroid
sangfroid

Reputation: 3803

In hibernate, is it possible to persist an object in the constructor?

So, the way I typically persist an object is to call entityManager.persist(object). Is there a way to persist an object in its own constructor, so I don't have to create a bunch of factory classes?

Likewise, is there a way to remove an object using an instance method?

Are either of these things good ideas, or should I be using an external class to do this stuff?

Upvotes: 0

Views: 318

Answers (2)

Ryan Stewart
Ryan Stewart

Reputation: 128849

Your EntityManager would have to be injected into the entity before the entity is constructed, which is only possible using AspectJ weaving or a static initializer, which would be a terrible way of doing it.

If you mean removing using an instance method of the entity, then yes, you can, assuming again that the EntityManager is available to that method somehow.

Generally speaking, an entity wouldn't be persisted on instance creation, but the other isn't necessarily atypical.

Upvotes: 0

matt b
matt b

Reputation: 139931

This is not a good idea, since Hibernate needs to call the object's constructor when it instantiates an instance of the object to return to you from a query.

In a clean design, your entity objects / domain model layer would not be aware of the persistence layer at all.

Upvotes: 2

Related Questions