Ejemplo de mapeo de Entidades con ModelMapper

¿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!

41 comentarios

  1. Thank you for sharing your info. I truly appreciate your efforts and I am waiting for your further post thanks once
    again.

  2. Why users still use to read news papers when in this technological world all is presented on net?

  3. 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!

  4. 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

  5. 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

  6. This web site is my inhalation, real superb pattern and Perfect
    content material.

    Look into my homepage … SynoGut Side Effects (meteoritegarden.com)

  7. Dead composed subject matter, thank you for entropy.

    my web site Alpha Edge Pills

  8. 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.

  9. 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

  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)

  11. 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.

  12. 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!

  13. 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

  14. I am regular reader, how are you everybody? This article posted at this web site is
    actually fastidious.

    my blog post :: Vigor Max

  15. Pretty! This has been an extremely wonderful post.

    Thanks for supplying this info.

    Feel free to surf to my blog – Green Earth CBD Gummies

  16. 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

  17. I read this article fully regarding the difference of latest and earlier
    technologies, it’s awesome article.

  18. 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. Great site you’ve got here.. It’s hard to find quality writing like yours nowadays.

    I truly appreciate people like you! Take care!!

  20. 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

  21. 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!

  22. 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!

  23. 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

  24. 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

  25. These are genuinely fantastic ideas in on the topic of blogging.

    You have touched some nice things here. Any way keep up wrinting.

  26. 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.

  27. 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.

  28. Woh I enjoy your content, saved to fav!

    Feel free to visit my page; Mega XL Advantage

  29. 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!

  30. What’s up, I log on to your blog like every week.

    Your story-telling style is awesome, keep it up!

  31. 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

  32. 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.|

  33. 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!

  34. salfluair disponible sin receta en farmacia de Bogotб dуnde comprar salfluair en Lyon

  35. 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?

  36. 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

  37. 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.

  38. 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 😉

  39. 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!

  40. Thanks designed foг sharing sucһ a fastidious tһought, piece of
    writing is pleasant, thatѕ why i have read it fulⅼy

3 pingbacks

  1. Pingback: meritking
  2. Pingback: meritking
  3. Pingback: meritking

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

La Ley 34/2002 nos obliga a avisarte de que usamos cookies propias y de terceros con objetivos estadísticos y de sesión y para mostrarte la 'publi' que nos da de comer. Tranquilo, este mensaje solo sale una vez. Más información

Java desde 0 comunica a los usuarios, a través de este aviso, que puede utilizar cookies cuando el usuario navega por las diferentes pantallas y páginas del sitio. Durante el uso de nuestra página Web usted acepta y autoriza expresamente el uso de cookies, de acuerdo con nuestra Política de Privacidad. Este sitio web utiliza las siguientes cookies propias: - Cookies de sesión, para garantizar que los usuarios que escriban comentarios en el blog sean humanos y no aplicaciones automatizadas. De esta forma se combate el spam. Este sitio web utiliza las siguientes cookies de terceros: - Google AdManager y AdSense: Utiliza cookies para mejorar la publicidad. Entre otros fines, suelen utilizarse para segmentarla según el contenido que sea relevante para los usuarios o su ubicación, mejorar los informes de rendimiento de las campañas y evitar mostrar anuncios que los usuarios ya hayan visto. Las cookies no contienen información personal identificable. Consulta cómo utiliza Google la información de sitios web o aplicaciones. y cómo bloquear determinados anuncios. - Google Analytics: Almacena cookies para poder elaborar estadísticas sobre el tráfico y volumen de visitas de esta web. Al utilizar este sitio web está consintiendo el tratamiento de información acerca de usted por Google. Por tanto, el ejercicio de cualquier derecho en este sentido deberá hacerlo comunicando directamente con Google. - Redes sociales: Cada red social utiliza sus propias cookies para que usted pueda pinchar en botones del tipo Me gusta o Compartir.

Cerrar