I have previously used Hibernate and now I am trying to understand JDBC. I have done loads of research on Spring JDBC but still I could not understand how to create relationships between objects.
Assume I have a Product:
public class Product {
private Long id;
private String nam;
private Customer customer;
//constructor, getters and setters.
}
and a Customer:
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 correctly save the product and customer objects in the db using SpringJDBC? Thank you
It make a lot of sense in quite a few cases to not use a full blown ORM but rely on lower level of abstraction, like Spring JDBCTemplate and RowMapper. iBatis comes to mind as well. And that make sense even in large enterprise solutions.
If you leave the full blown ORM world, you will have to do additional work yourself. For example, you can write an SQL query with a join, returning all customer fields and all products of that customer, and iterate through it to map all that to Java object. In quite a few cases, the code can be as clean as what you would have with an ORM.
Writing all that data is more messy, especially if you need to optimize for stuff that has not been dirtied.
Best use case I can think of is batch processing, where control over data access becomes more important and higher level of abstraction do not necessarily make you more productive.
If you are willing to consider something other than spring or hibernate, sormula can do what you describe. See the one to many example. If you name the foreign key on the many side the same as the primary key on the one side, then you don't need any annotations.
To store a reference to one-side object (Customer) in the many-side objects (Products), you can use the OneToManyCascade#foreignKeyReferenceField. For examples, search the tests in the project for "foreignKeyReferenceField".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With