I am currently in a dilemma and I've been reading stuff regarding this.
I am making my DTOs be also my Entities. It looks something like this:
@Entity
@PasswordMatches // custom validator
public class User {
@Id
@Column
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@Column
@NotNullOrEmpty // custom validator
private String password;
@Transient
@NotNullOrEmpty // custom validator
private String confirmPassword;
Q1: Is this acceptable or is there any better way of doing this? Because currently, before saving a User
I am hashing the password for obvious reasons but if I em.persist(user)
directly, it will fail because of @PasswordMatches
is failing. It's only saving when I do user.setConfirmPassword(hashedPassword)
just to satisfy the validation. Am I doing the right thing here?
While EJB3 allowed for the possibility of Entities being used as DTOs, the truth is it is still better to have separate DTOs.
Pretty soon you will find that your Entities will require annotations related to specific JPA Providers (like Hibernate) which will tie your Entities to the persistence layer. This will mean that if your Entities are passed 'up' to your presentation layer, then that layer needs to 'know' about the specific libraries/frameworks that you are using in your persistence layer. That's not much of a problem if you are doing web stuff, but if you are doing rich clients (e.g. Swing) then that can be extra baggage that your clients need to carry around.
Similarly, you will want to start annotating your Entities for the presentation layer (e.g. using @Json
annotations). Putting these in your entities will again tie your persistence layer to your presentation layer.
Initially we fell into the trap of using our Entities to pass data up to our rich clients, but we had created over 300 Entity classes by the time we realised we needed to separate them into DTOs and persistence Entities. It was a painful experience to do that with so many Entities, but now (with over 400 Entity classes) we are glad we did it.
So, while it is acceptable to do what you are doing, you have already run into an issue where mixing business logic with your persistence layer has caused a problem. I would recommend you separate these out into DTOs and Entities to save you continued problems in the future.
In short run, it seems productive and helps you in getting things done faster.
In the long run, it is always better to have DTOs and Entities separate.
As relationships between entities grow, you will realize that fetching one entity will result in child entities getting fetched as well, even though you may not need them in that specific use case. DTOs helps you to optimize your database queries the way you need keeping the underlying entities hidden from business use cases.
The answer also depends upon your use case. Consider these factors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With