Friday, April 25, 2025
HomeJavaSuppose twice earlier than utilizing an object mapping library to get your...

Suppose twice earlier than utilizing an object mapping library to get your DTOs


I typically get requested if I can suggest any object mapping library to map entity objects to DTOs. And you’ll find a number of discussions and articles about that on google. However as an alternative of asking which library you must use, you must first ask your self when you ought to map an entity to a DTO in any respect. As a result of in virtually all conditions, I like to recommend avoiding this mapping within the first place. And also you then don’t want any type of object mapping library. The reason being that when working with Hibernate, or another JPA implementation, this type of mapping removes all advantages of a DTO projection. And that’s, in fact, additionally the case when utilizing Spring Knowledge JPA.

If that’s all you needed to know, you’ll be able to cease studying this text. However I hope you’ll keep and let me clarify why object mapping libraries usually are not an incredible match for many of your use instances and what you must do as an alternative.
Earlier than we get into the small print, let me rapidly clarify what an object mapping library is.

What’s an object mapping library

An object mapping library maps an object of 1 class with all its attribute values to an object of one other class. Relying in your library and the similarity of the two courses, the item mapping library can deal with the mapping based mostly on predefined naming conventions or a small configuration file.

I’m not giving any examples of an object mapping library right here as a result of I don’t need to create the impression that I’m discrediting any particular library. There are a lot of nice object mapping libraries. They are often extraordinarily helpful for the fitting process, simplify your job and even keep away from bugs and efficiency issues.

It’s not the fault of the item mapping library that mapping an entity object to a DTO is normally not a good suggestion. The issue is attributable to the truth that you first must get an entity object, which you then map to a DTO. The best way JPA handles entities creates a noticeable overhead. And you’ll keep away from all of the overhead by instantly fetching unmanaged DTO projections.

OK, let’s dive somewhat deeper and focus on how JPA implementations deal with entity and DTO objects. To make the next sections somewhat simpler to know, I anticipate you to make use of Hibernate as your JPA implementation. All different JPA implementations work equally in order that the overall arguments are the identical even when the implementation particulars barely differ.

JPA’s dealing with of entity objects and the overhead it creates

While you fetch an entity object from the database, it turns into a managed object. Meaning it’s half of the present persistence context and has a managed lifecycle. This offers you many advantages:

  • When you change any entity object’s attribute, Hibernate routinely detects the change and decides when to execute the required SQL assertion. For efficiency causes, it tries to delay the execution of that assertion so long as doable.
  • Hibernate ensures that throughout the context of your present session, only one entity object represents a particular database document. You’re going to get the identical object when you fetch that document a number of instances.
  • When you name EntityManager‘s discover methodology or traverse a to-one affiliation, Hibernate first tries to get the item from the present persistence context / 1st-level cache. If it will get it from there, it doesn’t must execute an SQL SELECT assertion.

These are helpful options that simplify the implementation of write operations and may present efficiency advantages. However you don’t get them totally free. They arrive with just a few downsides:

  • When studying an entity object, Hibernate all the time initializes all primary attributes.
  • Hibernate fetches all eagerly fetched associations when it initializes an entity object.
  • Earlier than executing any question, Hibernate has to test the persistence context for modified managed entity objects that may be related to the question. If it finds any, it must execute the required SQL write operations to replace the database earlier than executing the question.
  • When processing the results of a question that returns entities, Hibernate checks the persistence context for every document to keep away from instantiating a brand new object for an already managed entity.

All of this takes time and assets. When you’re implementing a write operation, the beforehand listed benefits of managed entities outweigh these prices by an enormous margin.

However that’s not the case when you fetch entity objects from the database and instantly hand them over to an object mapping framework to map them to unmanaged DTOs. In that case, you’re solely getting the disadvantages of an entity projection with out reaping the advantages.

JPA’s dealing with of DTO objects and the overhead it avoids

DTOs are unmanaged objects. Meaning they don’t have any lifecycle, they don’t develop into a part of the persistence context, and Hibernate forgets about them after instantiating them. Attributable to that, they don’t have any administration overhead, and also you keep away from all of the downsides of managed entity objects. They’re additionally not mapped to a particular database desk, and you’ll design them based mostly on the wants of a particular use case.

As all the time, this additionally has just a few downsides. You possibly can’t use DTO objects to carry out any write operations when utilizing Hibernate or another JPA implementation. Hibernate doesn’t present lazy loading for any associations between totally different DTO objects. It additionally doesn’t be certain that you all the time get the identical object when you learn the identical info a number of instances.

So, by working with unmanaged objects, you not solely keep away from all of the downsides of entity objects, however you’re additionally dropping all of their advantages. That’s why I like to recommend checking your use case earlier than deciding whether or not to make use of entities or DTOs. When you don’t need to write any information to your database, you’re normally not benefiting from the benefits of managed entity objects. In that case, you must higher use DTO objects and luxuriate in their efficiency advantages.

Utilizing DTO objects is just one manner to enhance the efficiency of your persistence layer. If you wish to study extra about efficiency tuning, you must be part of the Persistence Hub. Apart from many different issues, that provides you entry to my Hibernate Efficiency Tuning course. It teaches you every thing that you must know to enhance the efficiency of your persistence layer.

Keep away from the overhead by avoiding object mapping libraries

After discussing how Hibernate handles entities and DTO objects, it’s time to speak about object mapping libraries. As I discussed earlier, I believe object mappers could be very helpful. However they’re solely not often a superb match to transform entity objects to DTOs. And when you learn the two earlier sections, you hopefully already know why.

While you fetch an entity object from the database and convert it to a DTO object, you continue to have the managed entity object in your persistence context. However you’re not utilizing it. You’re utilizing the DTO object your object mapping framework created. Meaning as an alternative of getting the advantages of a DTO object, you get all of the overhead of a managed entity object. On prime of that, you additionally get all of the disadvantages of the DTO object. So, in the long run, you’re simply combining the downsides of each approaches.

You possibly can keep away from that by fetching DTO objects instantly from the database as an alternative of fetching entities and mapping them to DTO objects. You are able to do that in numerous methods. The simplest one is utilizing a constructor expression in your JPQL question. Or you may use a Hibernate-specific ResultTransformer (Hibernate 4 & 5) or a TupleTransformer or ListTransformer (Hibernate 6).

The next code snippet reveals a primary instance of a constructor expression. It begins with the key phrase new adopted by the absolutely certified identify of the category you need to instantiate and a number of constructor parameters. Hibernate makes use of this info to name the described constructor for every document when processing the question outcome.

TypedQuery<BookWithAuthorNames> q = em
		.createQuery("""
				SELECT new com.thorben.janssen.BookWithAuthorNames(b.id, 
																   b.title, 
																   b.value, 
																   concat(a.firstName, ' ', a.lastName)) 
				FROM E-book b JOIN b.writer a 
				WHERE b.title LIKE :title
				""",
				BookWithAuthorNames.class);
q.setParameter("title", "%Hibernate Suggestions%");
Record<BookWithAuthorNames> books = q.getResultList();

As defined earlier, the principle advantage of this method is that Hibernate doesn’t instantiate any entity objects. It instantly instantiates a DTO object for every document within the outcome set.

When utilizing an object mapping library is OK

Thus far, I’ve defined in nice element why you shouldn’t map entity objects to DTOs. And that additionally explains why you shouldn’t use an object mapping library to get your DTOs.

However there are just a few conditions the place you already labored with an entity object and need to get an unmanaged DTO illustration of it. A typical instance is a use case that performs a write operation and returns the modified information. You clearly use entities to implement the write operation. And When you observe my suggestion to not expose entities in your API, that you must map these entities to DTOs.

In these conditions, you’ve 2 choices:

  1. Execute one other database question that selects the modified info and makes use of a DTO projection.
  2. Map the entity object to a DTO.

If the returned DTO and the entity object utilized in your use case are related, executing a further question doesn’t make a whole lot of sense. It solely slows down your utility with out getting any new info. In that case, an object mapping library supplies a snug method to map your entity object to a DTO. And utilizing it’s completely superb.

And that will get us again to the preliminary query: Which object mapping library do you have to use?

While you learn till right here, you’re in all probability not stunned if I inform you I don’t use object mapping libraries fairly often. But when I do, I normally select MapStruct. Thus far, it has labored very nicely for me.

Conclusion

Managed entity objects present a number of advantages but in addition create an overhead. You must all the time test if their advantages outweigh the overhead when utilizing them. That’s usually the case when implementing write operations however not when implementing read-only operations.

Attributable to that, you must keep away from fetching entities and instantly changing them to DTOs. If you wish to fetch DTOs from the database, you must use options like JPQL’s constructor expression or Hibernate’s TupleTransformer. They instantly instantiate an unmanaged DTO object for every document within the outcome set and keep away from the instantiation of entity objects.

The one state of affairs by which utilizing an object mapping framework is an choice is while you implement a write operation and need to expose a DTO illustration to the caller. You want entity objects to implement the write operation, and also you don’t get any advantages from executing a further question returning a DTO projection. So, in that case, it’s simpler to make use of an object mapping framework to map an entity to a DTO object.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments