Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

spring - DTO and Entity in one object?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...