Save multiple row data and some other data into two tables simultaneously in spring hibernate - spring

I want to save data of a form into two tables simultaneously. The form contains multiple identical rows with some fields like
item, unit, unit_price, total.
1.) In the table1 I would like to save some data like id(auto generated, primary key), date, creator.
2.) In table2 I would like to save the id(auto generated, primary key), fid(id of the table1, foreign key), item, unit, unit price, total. Remember, in table2 multiple rows will be save from the form data.
I can't figure it out. Please help me with a valid step by step example, and please don't use static or pre-defined data, take the data from form only.

Is your form an HTML form on a web page, and are you writing a Spring MVC application? Have you setup Spring Security, or some other authentication mechanism such that you know who the user is? If so, here is one approach:
Define a plain old Java object (POJO) with fields id, unit, unit-price, total, creator, currentDate; perhaps you would name it Item.
Define another plain old Java object perhaps named "ItemHistory", with its own ID and a reference to an Item.
In the first POJO ("Item") include a reference to a list of ItemHistorys.
Annotate both classes with Hibernate/JPA annotations, such that the Item has a OneToMany relationship to ItemHistory.
Define a Spring MVC controller with a method annotated as a POST method, with an Item as one parameter, and an Authentication as another parameter (supposing you have configured Spring Security, the Authentication will automatically be populated with the identity of the currently-logged-in user. In this method, set the currentDate and author of the Item to the current date and the principal from the Authentication parameter. If it is a new Item (no id yet), add the first ItemHistory as a copy of the Item itself. If it is an existing item, add another ItemHistory if needed.
Define a Spring bean, perhaps named ItemService, with a method annotated as transactional, that takes an Item and saves it. Call this bean from the REST controller. Such a Spring bean is known as a DAO (data access object).
There are other strategies, but if you already have Spring MVC, Spring Security, and Hibernate/JPA configured to your needs, this one is pretty straight-forward.

Related

Spring Boot how i can add Entity in table?

pls help me understand how i can add Entity in table.
(Use Tutorial) I create Spring boot app - login/registration/home - with Security, SpringJpa, Hibernate and Thymeleaf. Tutorial it is always cool, but can i do something without that?
I decide to expend my app, and understand that i am real beginner.
So, my problem, i have home.html page, with Courses (three courses), that i want to add in my new page cabinet.html one of this course. New page have empty bootstrap table, but i want add course and see this entity in table!
link to view html page https://drive.google.com/drive/folders/1dnn-IKkpaBeouyqnGU13YLf1GBPVd_jQ?usp=sharing
My Question, after registration and login, what i need to write in backend, that on of my course appear after (click button add) in List Table in the Cabinet?
I think this is may be :
Course Entity (id, string name, string date) that saves to MySQL. Courses Repository. Courses service with method find-All or save? ServiceImpl, Controller, PostMapping with RequestParam?
And what thameleaf tegs i need to add in my table that field courses entity views in table? Pls help

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.

Which way is better when insert a record to the database using id generator?

Because my project may be adapted to mysql or oracle,so I have a method that to produce id .When insert a new student record, the student record should call the method to produce the id. But what I'm curious about is when to call the method.Now my project is build by spring cloud. I should call the method in service module and pass the student object with id to the dao module. Or I pass the student object and the in the dao module,I call the id generator?
Which way is better?
Ok, i've decided to extend my comment.
In my opinion a better way would be to generate id inside dao, because you need id to save object in database, so you have to be sure that id is generated. For example if you have multiple clients and each client can save to database object student it would be difficult to make sure that each client uses id generator method in proper way. If you would use this method you don't need to take care about validation of id.
Moreover generating id inside dao follow low coupling principle.

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.

how can i update an object/entity that is not completely filled out?

I have an entity with several fields, but on one view i want to only edit one of the fields. for example... I have a user entity, user has, id, name, address, username, pwd, and so on. on one of the views i want to be able to change the pwd(and only the pwd). so the view only knows of the id and sends the pwd. I want to update my entity without loading the rest of the fields(there are many many more) and changing the one pwd field and then saving them ALL back to the database. has anyone tried this. or know where i can look. all help is greatly appreciated.
Thx in advance.
PS
i should have given more detail. im using hibernate, roo is creating my entities. I agree that each view should have its own entity, problem is, im only building controllers, everything was done before. we were finders from the service layer, but we wanted to use some other finders, they seemed to not be accessible through the service layer, the decision was made to blow away the service layer and just interact with the entities directly (through the finders), the UserService.update(user) is no longer an option. i have recently found a User.persist() and a User.merge(), does the merge update all the fields on the object or only the ones that are not null, or if i want one to now be null how would it know the difference?
Which technologies except Spring are you using?
First of all have separate DTOs for every view, stripped only to what's needed. One DTO for id+password, another for address data, etc. Remember that DTOs can inherit from each other, so you can avoid duplication. And never pass business/ORM entities directly to view. It is too risky, leaks in some frameworks might allow users to modify fields which you haven't intended.
After the DTO comes back from the view (most web frameworks work like this) simply load the whole entity and fill only the fields that are present in the DTO.
But it seems like it's the persistence that is troubling you. Assuming you are using Hibernate, you can take advantage of dynamic-update setting:
dynamic-update (optional - defaults to false): specifies that UPDATE SQL should be generated at runtime and can contain only those columns whose values have changed.
In this case you are still loading the whole entity into memory, but Hibernate will generate as small UPDATE as possible, including only modified (dirty) fields.
Another approach is to have separate entities for each use-case/view. So you'll have an entity with only id and password, entity with only address data, etc. All of them are mapped to the same table, but to different subset of columns. This easily becomes a mess and should be treated as a last resort.
See the hibernate reference here
For persist()
persist() makes a transient instance persistent. However, it does not guarantee that the
identifier value will be assigned to the persistent instance immediately, the assignment
might happen at flush time. persist() also guarantees that it will not execute an INSERT
statement if it is called outside of transaction boundaries. This is useful in long-running
conversations with an extended Session/persistence context.
For merge
if there is a persistent instance with the same identifier currently associated with the session, copy the state of the given object onto the persistent instance
if there is no persistent instance currently associated with the session, try to load it from the database, or create a new persistent instance
the persistent instance is returned
the given instance does not become associated with the session, it remains detached
persist() and merge() has nothing to do with the fact that the columns are modified or not .Use dynamic-update as #Tomasz Nurkiewicz has suggested for saving only the modified columns .Use dynamic-insert for inserting not null columns .
Some JPA providers such as EclipseLink support fetch groups. So you can load a partial instance and update it.
See,
http://wiki.eclipse.org/EclipseLink/Examples/JPA/AttributeGroup

Resources