Home > Back-end >  Do I need create new simple entity for query without join in jooq?
Do I need create new simple entity for query without join in jooq?

Time:05-17

I have some entity that look like that:

data class ComplexEntity(
   private val id: UUID,
   private val srcSomethingId: UUID,
   private val dstSomethingId: UUID,
   private val creationDate: LocalDateTime,
   private val updatingDate: LocalDateTime?,
   private val creationAuthorId: UUID,
   private val updatingAuthorId: UUID?,
   private val roles: List<UUID>,
   private val fieldsId: UUID,
   // relation
   private val srcSomething: SomethingEntity?,
   private val dstSomething: SomethingEntity?
)

It has relation and i'm joining it with another table, but I don't need the relation most of the time, so maybe I need to create more simplified entity like projection or just stay relation fields null when they are not needed.

data class ComplexProjection (
   private val id: UUID,
   private val srcSomethingId: UUID,
   private val dstSomethingId: UUID,
   private val creationDate: LocalDateTime,
   private val updatingDate: LocalDateTime?,
   private val creationAuthorId: UUID,
   private val updatingAuthorId: UUID?,
   private val roles: List<UUID>,
   private val fieldsId: UUID
)

Or vice versa stay ComplexProjection like main entity because it need most of the time and call it ComplexEntity and make ComplexEntityWithRelations where put relations.

What is the best way to do it?

P.S. Actually, I don't need all of this fields most of the times, but I think additional 5 field don't hurt performance so much.

CodePudding user response:

JPA entities are a way of modelling your data, similar to CREATE TABLE in SQL. If you normalise things reasonably, indeed, you don't have too many options, both in the form of SQL and in the form of JPA entities.

But, for all the wrong reasons, people also project those entities all the time, even if with JPA, you can project arbitrary data structures, just like with jOOQ. Your data classes aren't entities, they're projections. It's not the same thing. Like in SQL, where you can write arbitrary views for your data, and SQL wouldn't tell you to do it this or that way, jOOQ has no opinion about your projections.

So, the process is this:

  1. Normalise your schema to a sufficient level (e.g. 3NF)
  2. Design your queries according to your needs (e.g. the UI needs these 3 columns from table A and these 2 nested collections from table B)

That's it. The best query and thus the best projection for your individual needs arise naturally, from your (team's) preferences, your data representation, requirements, etc. There's no right or wrong projection of your data, as long as you can represent things in a reasonable way.

  • Related