Spring Data JPA and Database Relationships
Check out Spring Data JPA and database relationships.
Join the DZone community and get the full member experience.Join For Free
originally published on january 31, 2015
how do we implement database relationships using spring data jpa?
there are a lot of real-world objects that impact a business case. of those, a few of them impact a specific use case of a business. once we identify the real-world objects that impact the specific business use case, then a database model is created. to be more precise, an entity-relationship diagram is made from that information. there would be a lot of relationships among those business objects or entities, which have to be implemented in the software.
you might also like: spring boot with spring data jpa
a relationship works by matching data in key columns — usually columns with the same name in both tables. in most cases, the relationship matches the primary key from one table, which provides a unique identifier for each row, with an entry in the foreign key in the other table.
let’s say we are working for a telecommunication vendor who wants to track his customers who have been shifting from one location to another and asking for a new connection every time they move to a new location.
so, in this case, a customer will be associated with an account. this account is tied to a specific location, which has the zip code. this seems to be that one customer can have only one account at a given location. if the same customer is allowed to have multiple accounts at a location, then it means that one customer can have multiple accounts at a location.
this is an example of a one-to-many relationship. similarly, that location can have multiple accounts. this leads to a many-to-one relationship between account and location. since the same customer is tied to the location, it is a one-to-one relationship between them. there are three types of relationships between tables. the type of relationship that is created depends on how the related columns are defined.
1. one-to-many relationship
a one-to-many relationship is the most common type of relationship. in this type of relationship, a row in table a can have many matching rows in table b, but a row in table b can have only one matching row in table a. in the above example, a customer can have many accounts for a given location. so it’s a one-to-many relationship.
2. many-to-many relationships
in a many-to-many relationship, a row in table a can have many matching rows in table b and vice versa. in the above example, one customer can have many accounts at one location. so there can be many-to-many relationships in between accounts and customers, provided a new customer id is given for a new account and is not tied to the same customer id. one can also maintain such a relationship by defining a third table, called a junction table, whose primary key consists of the foreign keys from both table a and table b. this might not be really required.
3. one-to-one relationships
in a one-to-one relationship, a row in table a can have no more than one matching row in table b and vice versa. a one-to-one relationship is created if both of the related columns are primary keys or have unique constraints. so in the above example, one customer can be tied to one location.
there are multiple ways of solving this in java space. the following are the technologies:
1. plain jdbc using a jdbc driver
2. spring data jpa using hibernate
3. spring jdbc which is essentially plain jdbc in itself
4. giving the objects to rdbms with data to persist it. essentially, it’s the rdbms layer that can take care of the persistence.
in this article, i will be talking about how to persist this using spring data.
step 1: use tools like sts, which has built-in provision to create an entity object.
then you would see:
enter “jpa project” to create a jpa project. here you can enter the value as per your understanding.
click next unless you want to do some configurations.
try to add a connection to a new connection.
pick the database type.
enter the connection details.
upon completion of this, spring data jpa will create the java files for you, which are required for the execution of the project. these java files will have the entity and the column mappings. please make sure that you have the @id mapping or you will have a hibernate exception.
now, in order to implement the one-to-many relationships, make sure that you have the line defined in the customer class.
@onetomany(cascade = cascadetype.all, orphanremoval = true,mappedby="account")
here, the @onetomany relationship makes sure that the one customer has many accounts. now in the account class, make sure that you have:
@manytoone(cascade=cascadetype. all )
@joincolumn(name=" account_id",nullable= false )
private customer customer;
this ensures that the many-to-one relationship is established.
if you are creating a new child record for an existing parent, it’s essential to associate the child with the parent. you can create a record in the child table by giving a parent id. but spring data jpa asks for the parent record so as to be able to create the child.
transactions and spring data jpa
it’s quite essential to understand how transactions and spring data jpa work together. transactions have the following propagation levels:
support a current transaction; throw an exception if none exists.
execute within a nested transaction if a current transaction exists, behave like propagation_required else.
execute non-transactionally, throw an exception if a transaction exists.
execute non-transactionally, suspend the current transaction if one exists.
support a current transaction, create a new one if none exists.
create a new transaction, and suspend the current transaction if one exists.
support a current transaction, execute non-transactionally if none exists.
transactions have the following isolation levels:
use the default isolation level of the underlying datastore.
a constant indicating that dirty reads are prevented; non-repeatable reads and phantom reads can occur.
a constant indicating that dirty reads, non-repeatable reads, and phantom reads can occur.
a constant indicating that dirty reads and non-repeatable reads are prevented; phantom reads can occur.
a constant indicating that dirty reads, non-repeatable reads, and phantom reads are prevented.
now when you are wanting to call the transactions, please make sure that the isolation levels that have been used are correct. also, make sure that the propagation level over the method is done correctly.
how to achieve the batch insert using spring data jpa?
the jparepository has methods that have the provision to accept a collection of objects. this collection can be used to persist the records. please do not assume that this is a batch insert. it’s not. the <s extends t> list<s> save(iterable<s> entities) and actually iterates through the collection and saves record one by one.
after going through this article, you can replicate the entity-relationship diagram into spring data jpa entities and appropriately use the transactions to save them into the database. by using spring data jpa, you leave the responsibility of the database with the spring jpa api. this way, you can focus on the business functionality more than on the technical complexities of the database relationships.
Opinions expressed by DZone contributors are their own.