Mapping objects in Spring JDBC?

I previously used Hibernate, and now I'm trying to understand JDBC. I did a lot of research on Spring JDBC, but still I couldn't figure out how to create relationships between objects.

Suppose I have a Product:

public class Product { private Long id; private String nam; private Customer customer; //constructor, getters and setters. } 

and client:

 public class Customer { private Long id; private String name; private List<Product> products = new ArrayList<Product>(); //constructor, getters and setters } 

The relationship between Customer and Product is @OneToMany. How to store product and client objects in db correctly using SpringJDBC? Thanks you

+5
source share
3 answers

In some cases, it’s very important not to use a full-blown ORM, but to rely on a lower level of abstraction, such as Spring JDBCTemplate and RowMapper. iBatis also comes to mind. And it makes sense even in large corporate solutions.

If you leave the whole world of ORM, you will have to do the extra work yourself. For example, you can write a SQL query with a connection, returning all client fields and all products of this client and iterating over it to match all this with a Java object. In quite a few cases, the code may be as clean as yours with ORM.

Writing all this data is more random, especially if you need to optimize material that has not been contaminated.

The best use case I can think of is batch processing, where control over data access is becoming more important, and a higher level of abstraction does not necessarily make you more productive.

+4
source

If you want to consider something other than spring or hibernate, sormula can do what you describe. See Example one to many . If you name the foreign key on the side from the side in the same way as the primary key on one side, then you do not need annotations.

To keep a reference to a one-way object (Customer) in many side objects (Products), you can use OneToManyCascade # foreignKeyReferenceField . For example, search the project for "foreignKeyReferenceField".

+1
source

If I understand your question correctly, if you think that if you are not using ORM, you will have to do it manually. In your DAO class for Customer, you will first need to save all the products.

An alternative would be to create a stored procedure in the database and eliminate the correctness of its storage.
This can be handled very well with Spring JDBC, the disadvantage is that you know that you need to manage Java and stored procedures. In your case, it can be two stored procedures.

There is also the possibility that QueryDSL and Jooq thought that I was not able to look at them well.

I personally like the solution with the stored procedure, it is useful for me because I know that others do not agree, but I just do not like / buy the ORM transaction.

0
source

Source: https://habr.com/ru/post/1206005/


All Articles