users@jpa-spec.java.net

[jpa-spec users] Re: Proposal: allow JPA entities not to have a default no-arg constructor

From: Oliver Gierke <ogierke_at_vmware.com>
Date: Wed, 16 Nov 2011 02:31:47 -0800

Hi all,

as a follow up on this one…

> Another question that plays into this is that I am wondering what the rationale behind limiting the results of constructor expressions in queries to be in new or detached state? I can perfectly understand why this is the case for (non-entity) DTOs. Nevertheless I think it might make sense to let an entity in its entirety be constructed from such an expression. Why shouldn't it be in a managed state? E.g.
>
> @Entity
> class User {
>
> @Id
> @GeneratedValue
> private Long id;
>
> private String firstname;
> private String emailAddress;
>
> public User(String emailAddress) {
> Asser.hasText(emailAddress);
> this.emailAddress = emailAddress;
> }
>
> protected User() {}
>
> –
> }
>
> Why shouldn't I be able to define a query "select new User(u.emailAddress) from User u" forcing the persistence provider to use a particular constructor in that scenario and just get the entity back in the same state as if I had queried "select u from User u"?

I re-read up the spec on entity states. The 2.1 draft says, that the entity is in detached state if the primary key is read. So I am assuming the entity is in the detached state due to the assumption that actual fields of the entity about to be created are not expected to be populated, right? So IMHO it would be cool if the spec was a bit more precise about that area and actually defines the expected behavior as "use the constructor but populate the entity's properties nevertheless". I think if you really need strong projections to a set of fields only you'd rather introduce a dedicated DTO anyway as you might carry around the entity half populated and potentially violate object invariants.

Regards,
Ollie

-- 
/**
 * @author Oliver Gierke - Senior Member Technical Staff
 *
 * @param email ogierke_at_vmware.com
 * @param phone +49-351-30929001
 * @param fax   +49-351-418898439
 * @param skype einsdreizehn
 * @see http://www.olivergierke.de
 */