Spring data with R2DBC(Mysql) Example for one to many association - spring

Can I know how to do association(One to Many) in Spring data JDBC with R2DBC(Mysql).Please provide small code example or git link if possible.
For Example, I have one employee table and address table is child of employee.
One employee can have multiple addresses.
If I want to retrieve employee, I want address as well to corresponding employee as JSON.
Note: Software stack is Spring Functional Reactive, R2DBC with Mysql

Spring Data R2DBC currently does not support aggregates.
This means every entity gets mapped to just one table and can't have object references to other entities.
Therefore the correct way to model your example is to have no object reference between Empolyee and Address but have an employeeId in the Address and use that to select the desired addresses.

Related

Sprind Boot Controller When Using Hibernate #Inheritance (Single Table)

I've seen a lot of information on the different inheritance strategies but can't seem to find anything on how you setup a REST controller when using a single table strategy. In my scenario, I have 2 Barcode types: product and case.
I created a Barcode superclass that ProductBarcode and CaseBarcode inherit from. However, I have the following questions regarding how to implement this:
Do I need separate repositories for ProductBarcode and CaseBarcode?
Can I use a single endpoint to create/update/delete both kinds of Barcodes?
I have another entity (Product) that relates to Barcode and needs to be able to get the details for a barcode based on an ID. Product won't know what type of Barcode the ID belongs to. Is this something that will cause an issue?
To summarize what I'm trying to do:
Create a barcode entry of either ProductBarcode or CaseBarcode by sending a JSON POST request to a single endpoint such as localhost:8080/barcodes.
Retrieve or update a barcode of either type from a single endpoint.
Be able to perform CRUD operations without needing to know which type of Barcode is being operated on.
Is this something that is doable using Spring Data JPA and Hibernate? Thanks for any advice.

What would happen if entity model has relations but data (views) in database doesn't have relations and if they are inconsistent?

My question is would Spring JPA throw exceptions for every query?
I mean, let say there are tables without any relation (FK) between them in database. It is bad design but you cannot change it and it is not up to you.
But you know that data itself should be as there are relations.
That's why you create Entity model with all relations like they are there.
But as I said there is no real relations in database.
And in one point data are inconsistent in database.
Would Spring JPA throw exceptions if there are inconsistency or it will just return you inconsistent data?
I assume with "relations" you mean "foreign keys".
JPA doesn't care about foreign keys.
All it cares about is if the data matches the mapping information on the entities.
So if you have an entity A that references an entity B with id b but such a B does not exist you might eventually get an exception.
Or you might just get an A with a null reference to B.
If the reference is marked as mandatory you might actually not be able to load the A in the first place, because a join is used and therefore not returning any data at all.
Side note: All this depends more on the JPA implementation you are using than on Spring Data JPA.

Spring data JPA save() return less/incorrect child and parent association mapping fields [duplicate]

I'm developing a RESTful webservice with spring-data as its data access layer, backed by JPA/Hibernate.
It is very common to have relationships between domain entities. For example, imagine an entity Product which has a Category entity.
Now, when the client POSTs a Product representation to a JAX-RS method. That method is annotated with #Transactional to wrap every repository operation in a transaction. Of course, the client only sends the id of an already existing Category, not the whole representation, just a reference (the foreign key).
In that method, if I do this:
entity = repository.save(entity);
the variable entity now has a Category with only the id field set. This didn't surprise me. I wasn't expecting a save (SQL insert) to retrieve information on related objects. But I need the whole Product object and related entities to be able to return to the user.
Then I did this:
entity = repository.save(entity);
entity = repository.findOne(entity.getId());
that is, retrieve the object after persisting it, within the same transaction/session.
To my surprise, the variable entity didn't change anything. Actually, the database didn't even get a single select query.
This is related with Hibernate's cache. For some reason, when in the same transaction, a find does not retrieve the whole object graph if that object was previously persisted.
With Hibernate, the solution appears to be to use session.refresh(entity) (see this and this). Makes sense.
But how can I achieve this with spring data?
I would like to avoid to create repetitive custom repositories. I think that this functionality should be a part of spring data itslef (Some people already reported this in spring data's forum: thread1, thread2).
tl;dr
References between entities in the web layer need to be made explicit by using links and should not be hidden behind semi-populated object instances. References in the persistence layer are represented by object references. So there should be a dedicated step transforming one (the link) into the other (the fully populated object reference).
Details
It's an anti-pattern to hand around backend ids as such and assume the marshaling binding doing the right thing. So the clients should rather work with links and hand those to the server to indicate they want to establish a connection between an already existing resource and one about to be created.
So assuming you have the existing Category exposed via /categories/4711, you could post to your server:
POST /products
{ links : [ { rel : "category", href : "/categories/4711" } ],
// further product data
}
The server would the instantiate a new Product instance, populate it with additional data and eventually populate the associations as follows:
Identify properties to be populated by looking up the link relation types (e.g. the category property here.
Extract the backend identifier from the given URI
Use the according repository to lookup the related entity instance
Set it on the root entity
So in your example boiling down to:
Product product = new Product();
// populate primitive properties
product.setCategory(categoryRepository.findOne(4711));
productRepository.save(product);
Simply posting something like this to the server:
POST /products
{ category : {
id : 1, … },
…
}
is suboptimal for a lot of reasons:
You want the persistence provider to implicitly persist a Product instance and at the same time 'recognize' that the Category instance referred to (actually consisting of an id only) is not meant to be persisted but updated with the data of the already existing Category? That's quite a bit of magic I'd argue.
You essentially impose the data structure you use to POST to the server to the persistence layer by expecting it to transparently deal with the way you decided to do POSTs. That's not a responsibility of the persistence layer but the web layer. The whole purpose of a web layer is to mitigate between the characteristics of an HTTP based protocol using representations and links to a backend service.

Association mapping in microservice

I have two Microservices. Let's say student & library.
student & library - eureka clients
The microservices have a common DB
The scenario is - A student can issue (or take) multiple books from the library.
In Monolithic Application:- This will be implemented by anotating#OneTOMany on List of LibraryBook in StudentEntity and adding one table where we will store each book id for student.
Currently what i have tried
I have loose mapping (or binding ) of data between the data. I have created a table in DB with two columns studentId and bookId and when a student takes a book from library I add the bookId in the table and delete the record when book is returned.
For saving -
StudentBook studentBook = new StudentBook();
studentBook.setStudentId(123);
studentBook.setBookId(456);
studentBookRepository.save(studentBook); // studentBookRepository extends JPA Repository
For Deleting-
studentBookRepository.deleteByBookIdAndStudentId(456,123);
The problem in this implementation is that I always have to verify the bookId before saving the records.
Is there any better way to implement this?
How to implement #OneToMany relationship in Microservices?
(Or can we even implement Association mapping in microservices)
(Or can we even implement Association mapping in microservices)

maintain mvc architecutre in Spring MVCf 3

I have two tables that have relationship like
tbl_department whose entities are dept_id and dept_name where dept_id is primary key and next table is tbl_employee whose entities are emp_id, emp_name and dept_id where dept_id is foreign key that references the dept_id of tbl_department. Now, in my jsp page i want to display the format like this:
Emp_id|Emp_name|dept_name.
I am doing above display in JSP page using the JSTL sql tag, and I know it violates the MVC architecture, so, how could I solve this problem i.e. how can I do this relationship mapping it in either Model or Controller in Spring instead in JSP page. Is there any examples or tutorial I can find for this kind of problem
Thank you
First, you have to decide whether it would be worth your while using Hibernate. You should research this yourself to decide whether the rest of your app would benefit from using it (too big a topic to address here).
Assuming you only want to do the use case you have outlined in the question, I'd suggest you use Spring's JDBC support and create a Service (or just a DAO) to perform the SQL that you are currently using in your JSP. I'd create a simple DTO class to hold the Emp_id|Emp_name|dept_name data and populate that in your Service/DAO and then pass it to the JSP via the Controller.
This Spring MVC Example (skeleton) app would be a good place to start, to see how those components are created and wired together.

Resources