¿QUE NOS PROPORCIONA MODELMAPPER? Y ¿POR QUÉ USAR MODELMAPPER?
En muchos casos, como ya nos pasó a nosotros anteriormente en el artículo Relaciones @One-to-One (JPA) las aplicaciones requieren objetos que aunque son muy similares en cuanto a estructura/necesidades tienen entre ellos leves modificaciones. El mapeo tiene la finalidad de facilitar la conversión, el traspaso de unos datos de un objeto entity a otra entity.
El objetivo de ModeMaper es hacernos el mapeo entre objetos más sencillo, para ello, tenemos que definir el modelo (en este caso, el objeto inicial) que se mapeará y el modelo final (en este caso, el objeto final) sobre el que volcará los valores mapeados.
BENEFICIOS DE MODELMAPER
Algunos de los beneficios de utilizar ModelMaper son:
- Basado en convenciones e inteligente: no necesita un mapeo manual (a excepción de los campos cuyos nombres no coincidan tanto en nombre como en tipo de dato).
- API simple y segura: al no picar nosotros el código manualmente y hacerse automáticamente por detrás evitamos la posibilidad de que se produzcan posibles fallos.
- Extensible: admite diferentes formatos de modelos de datos. JavaBeans, JSON, BBDD…
URL Web Oficial: http://modelmapper.org/
Para utilizar modelMaper, necesitamos primeramente añadir la dependencia de Maven al pom.xml:
Aunque nos falta añadir la dependencia de modelmapper que no se encuentra en dicho asistente del STS4:
SISTEMA MANJEADOR DE BASES DE DATOS (SGBD)
El motor de BBDD sobre el que trabajaremos será MySQL WorkBech.
DIAGRAMA DE LA BBDD
SCRIPT BBDD:
SELECT * DE LA TABLA
APPLICATION.PROPERTIES
ENTITY
Person:
REPOSITORY
PersonRepository:
SERVICE
PersonService:
Por el momento dejaremos el servicio que nos devuelva todos los resultados. Una vez verifiquemos que funciona, empezaremos a modificar el servicio para que podamos realizar el mapeo con ModelMaper.
CONTROLLER
Por el momento, vamos a crear un controlador tradicional p
PersonRepository:
Si testeamos la aplicación, podemos ver que nos devuelve los resultados correctamente:
Ahora vamos a crear otro objeto entity sobre el package entity para poder realizar el mapeo de los objetos a posteriori con ModelMaper.
En la clase controlador, debemos hacer una leve modificación para modificar la entidad que devolverá el controlador antiguamente era Person y a partir de ahora será PersonRest.
Y para poder trabajar con moderMaper vamos a ir a a la capa de servicio que es la que contiene la lógica de negocio y vamos a trabajar con la clase ModelMapper mediante a la que realizaremos el mapeo. Vamos a ver un ejemplo:
Si queremos realizarlo con expresiones lamba obtenemos un resultado bastante más elegante.
Pese a que podemos ver que le mapeo se nos a realizado exitosamente, nos encontramos con el problema de que como hemos añadido dos campos más, estos dos están vacíos.
Para resolver esto y viendo que dichos campos dependen otros campos sobre los que ya tenemos la información, vamos a utilizar la anotación de Lombok @Setter(AccessLevel.NONE)
con la cual desactivamos los Getters por defecto y así podemos crear unos nuestros y gracias a esta anotación cogerá los nuestros y no los que genera automáticamente Lombok. Y finalmente, creamos los setters.
Y en el servicio justo antes de añadir el objeto a la lista, metemos una llamada a los dos setters que acabamos de crear desde le objecto PersonRest, no desde person, ya que person no tiene esos campos.
Y con lambda poco nos podemos ahorrar pero sería algo así:
Finalmente, el resultado será muy similar al resultado anterior, pero esta vez, sí que tenemos todos los atributos de la entidad/objeto rellenos.
Esto es todo por hoy. ¡Un saludo Javer@s!
19 agosto, 2021 a las 1:22
Thank you for sharing your info. I truly appreciate your efforts and I am waiting for your further post thanks once
again.
19 agosto, 2021 a las 1:32
Why users still use to read news papers when in this technological world all is presented on net?
19 agosto, 2021 a las 2:10
great publish, very informative. I wonder why the other experts of this sector don’t understand this.
You should proceed your writing. I am confident, you’ve a
great readers’ base already!
19 agosto, 2021 a las 2:34
Thank you for your site post. Jones and I happen to be saving for a new e book on this matter and your short article has made people
like us to save the money. Your thinking really clarified all our concerns.
In fact, a lot more than what we had acknowledged previous to the time we stumbled on your excellent
blog. I no longer nurture doubts and a troubled mind because you
have totally attended to each of our needs here. Thanks
my web blog: Vibrance Labs Ketoroll
19 agosto, 2021 a las 3:03
Great blog here! Also your site loads up very fast! What host are you using?
Can I get your affiliate link to your host? I wish my website loaded up as quickly as yours lol
19 agosto, 2021 a las 3:24
This web site is my inhalation, real superb pattern and Perfect
content material.
Look into my homepage … SynoGut Side Effects (meteoritegarden.com)
19 agosto, 2021 a las 3:53
Dead composed subject matter, thank you for entropy.
my web site Alpha Edge Pills
19 agosto, 2021 a las 5:50
What’s up, this weekend is nice designed for me, since this
point in time i am reading this enormous informative piece of writing here at my home.
19 agosto, 2021 a las 5:52
There is perceptibly a lot to know about this. I assume you made some nice points in features also.
Also visit my website Natural Burn Keto Review
19 agosto, 2021 a las 7:10
Great post! We will be linking to this particularly great
post on our website. Keep up the good writing.
My page … ColonBroom Review (beauty-inc.ru)
19 agosto, 2021 a las 7:49
If some one wants expert view about blogging then i propose him/her to pay a visit this web
site, Keep up the good work.
19 agosto, 2021 a las 9:29
I absolutely love your site.. Pleasant colors & theme. Did you develop this amazing site yourself?
Please reply back as I’m wanting to create my very own blog and would like
to find out where you got this from or what the theme is called.
Thanks!
19 agosto, 2021 a las 10:04
Wonderful beat ! I wish to apprentice even as you amend your website, how could i subscribe for a blog
website? The account helped me a applicable deal. I were tiny
bit acquainted of this your broadcast offered vibrant clear concept
19 agosto, 2021 a las 10:09
I am regular reader, how are you everybody? This article posted at this web site is
actually fastidious.
my blog post :: Vigor Max
19 agosto, 2021 a las 10:38
Pretty! This has been an extremely wonderful post.
Thanks for supplying this info.
Feel free to surf to my blog – Green Earth CBD Gummies
19 agosto, 2021 a las 10:59
These are really enormous ideas in concerning blogging. You
have touched some nice factors here. Any way keep up
wrinting.
my webpage :: Pure Keto Burn Ingredients
19 agosto, 2021 a las 11:53
I read this article fully regarding the difference of latest and earlier
technologies, it’s awesome article.
19 agosto, 2021 a las 12:25
Does your blog have a contact page? I’m having trouble locating it but, I’d like to shoot
you an e-mail. I’ve got some creative ideas for your blog you might be interested in hearing.
Either way, great website and I look forward to seeing it improve over time.
19 agosto, 2021 a las 13:30
Great site you’ve got here.. It’s hard to find quality writing like yours nowadays.
I truly appreciate people like you! Take care!!
19 agosto, 2021 a las 13:50
I visited several web sites however the audio quality for audio songs current at this website is genuinely fabulous.
Also visit my site … Libido Boost Pills Reviews
19 agosto, 2021 a las 14:06
I don’t even know how I ended up here, however I believed this post was great.
I don’t understand who you are but certainly you’re going to a famous blogger if you aren’t already.
Cheers!
19 agosto, 2021 a las 14:16
What i don’t understood is in fact how you are now not actually a lot more smartly-appreciated than you may be now.
You are very intelligent. You realize thus significantly with regards to this subject, made
me personally believe it from so many numerous angles. Its like men and women don’t seem to be involved except it’s something to accomplish with
Woman gaga! Your personal stuffs nice. At all times handle
it up!
20 agosto, 2021 a las 15:04
Everything is very open with a precise description of the
challenges. It was really informative. Your site is extremely helpful.
Thank you for sharing!
My webpage; Infinuity CBD Review
21 agosto, 2021 a las 8:38
Fantastic beat ! I would like to apprentice while you amend
your website, how can i subscribe for a weblog site? The account helped me a appropriate deal.
I were a little bit familiar of this your broadcast offered brilliant clear concept
Also visit my homepage Renown CBD Oil
24 agosto, 2021 a las 12:42
These are genuinely fantastic ideas in on the topic of blogging.
You have touched some nice things here. Any way keep up wrinting.
28 agosto, 2021 a las 12:12
I’m gone to tell my little brother, that he should also go to see this blog on regular basis to take updated
from most up-to-date information.
30 agosto, 2021 a las 8:36
Hi, I do think this is a great site. I stumbledupon it 😉
I am going to return once again since i have
book marked it. Money and freedom is the best way
to change, may you be rich and continue to help others.
20 septiembre, 2021 a las 17:51
Woh I enjoy your content, saved to fav!
Feel free to visit my page; Mega XL Advantage
24 noviembre, 2021 a las 0:35
Very nice post. I simply stumbled upon your blog and
wanted to say that I’ve truly loved surfing around
your blog posts. After all I will be subscribing for your
rss feed and I’m hoping you write again soon!
23 diciembre, 2021 a las 20:34
What’s up, I log on to your blog like every week.
Your story-telling style is awesome, keep it up!
27 noviembre, 2022 a las 19:40
Thanks for another magnificent article. The place else
may just anyone get that kind of info in such an ideal manner of writing?
I’ve a presentation subsequent week, and I’m on the search
for such information.
Also visit my web-site … tracfone special coupon 2022
17 abril, 2023 a las 9:49
What’s Going down i am new to this, I stumbled upon this I’ve discovered It absolutely useful and it has helped me out loads. I am hoping to give a contribution & aid other users like its helped me. Good job.|
9 julio, 2023 a las 2:56
It’s a shame you don’t have a donate button! I’d most certainly donate to this excellent blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to brand new updates and will talk about this site with my Facebook group. Chat soon!
28 julio, 2023 a las 3:58
best generic cialis PMID 29201466 Free PMC article
1 agosto, 2023 a las 21:45
salfluair disponible sin receta en farmacia de Bogotб dуnde comprar salfluair en Lyon
18 marzo, 2024 a las 21:43
I was wondering if you ever thought of changing the structure of your blog?
Its very well written; I love what youve got to say. But
maybe you could a little more in the way of content so people could connect with
it better. Youve got an awful lot of text for only having 1 or two pictures.
Maybe you could space it out better?
21 marzo, 2024 a las 19:54
Thіs iis rеally fascinating, Ⲩou’re a veгy professional blogger.
Ι’ve joined y᧐ur rsss feed аnd looқ ahead to in quest of moгe of yoᥙr wondeerful
post.Additionally, Ι’ѵe shared your website iin my social
networks
22 marzo, 2024 a las 6:22
I really lіke ѡhat you guys tend tto bee ᥙp too.
This қind of clever woгk and coverage!
Kеep up the fantastic workѕ guys І’ve addeɗ yоu guys t᧐ blogroll.
24 marzo, 2024 a las 23:24
I have to thank you for the efforts you’ve put in penningthis blog. I am hoping to check out the same high-grade content by you in the future as well.In truth, your creative writing abilities has inspired meto get my own, personal blog now 😉
25 marzo, 2024 a las 17:18
Tһiѕ design is wicked! Ⲩⲟu mоѕt certainly know hoᴡ to keеp a rearer entertained.
Bеtween yoսr wiit and your videos, I was almօst moved tⲟ staqrt my
own bllog (weⅼl, aⅼmost…HaHa!) Fantastic job.
Ι rеally enjoyed what you hаd to say, ɑnd more than thɑt,
how уou presented іt. Too cool!
26 marzo, 2024 a las 7:12
Thanks designed foг sharing sucһ a fastidious tһought, piece of
writing is pleasant, thatѕ why i have read it fulⅼy