How to map form to entity in spring

1k views Asked by At

In my application I have two separate class: 1. UserRegistrationForm class is a form backing object what I use to validate fields on server side. 2. UserEntity is ORM class what maps user table in database to Java object.

UserRegistrationForm and UserEntity have mostly the same fields like username, email etc., but they also vary a little bit e.g. UserRegistrationForm has additional retypedPassword and acceptTerms field.

For now my app works this way: 1. App gets input from user. 2. UserRegistrationForm perform validation. 3. If there is no errors UserRegistrationForm is mapped to UserEntity. 4. UserEntity is saved in database.

I'm wondering if this is a good design. Maybe I should have validation directly in my UserEntity? Or maybe there is a way to automatically map form backing object to entity?

1

There are 1 answers

1
Md. Naushad Alam On BEST ANSWER

I had also faced same problem few days ago and became confuse about formValidation object with mapping of Database Entity object.

The solution is, In formValidation, it is usual case that it has many fields those are not directly related with one DB Enity, rather it has some fields those come from few other DB Entitys(or tables) and also some fields those are not related with DB Entity.

In this case the standard way is validate the form, then map the fields with corresponding DB Entitys and last one, save into Database.

The process you have followed is right.