简体   繁体   中英

Why we should use Spring Data JPA mappings?

This can seem a stupid questions for some people, but I couldn't find any information anywhere why we should use mappings ( @OneToOne , @OneToMany etc) in JPA while defining entity classes. I know one the advantage is code reduction, so that we don't have to explicitly write queries in order to fetch data from relationship tables. But is there any other benefit (from code optimisation perspective at SQL side) that we have?

The reason is to load object trees or graphs.

That's the goal of object-relational mapping to fill the gap between database tables and objects.

And as you said it reduces code.

In a summary the idea of the ORM is to map tables to objects, so the developer works with the objects instead of the tables.

Tables in SQL have relationships through key columns. in JPA these relationships are expressed via @OneToMany, @OneToOne etc.

This means that if you want to fetch a row from one table and join that with corresponding row from another table (via a relationship) the JPA implementation (mostly Hibernate) can do that for you, looking at the relationships you have defined for your entities.

You need to describe the entities relationships because it's part of the DB schema model which you are mapping to application level objects. As you mention - it saves you writing the SQL queries yourself, but that's not the main point.

The main point is that you can model/represent one domain (database tables, rows, relationships, SQL commands) as another type of domain (objects/classes, OOP paradigm, programming language commands) which completely shifts the way you work with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM