written by Ivan Cerrato, reviewed by Ciro Cardone
next
JEE Tomcat Spring Maven Hibernate MySql Eclipse jsp Ajax
back to home
Spring_4. Hibernate one to many. In this fourth  part, We will write about the Hibernate one-to-many relationship by means of our web app, that will be enriched of some new part. In detail, we will talk about the relationship among user and item. There’s a relationship one-to-many among the two entities because a user can have, in this business design, more than one item.  This time we start making a look change to the web app; let’s start adding a blank style.css file in the resoure directory; after that we  need to reference it in the jsp page adding  "  />  We will put in the css the UI attributes of the html elements  obtained from jsp rendering. /*-------------*/ /* global CSS */ /*-------------*/ .c_div_1 {     float:left;     align:left;     margin-top:30px;     margin-bottom:30px; } .c_table_1 { font-family: "Helvetica Neue"; font-size:13px; color:#333333; /* border-collapse:collapse; */ font-size:1em; border:1px solid #0000FF; } .c_table_1 caption   { border:2px solid #FF0000; } .c_table_1 td  { border:1px solid #DCDCE6; } The css, nothing of special, is necessary to add some stylish to our new table. The css add some directives to the div that will contain the table and set the font and  borders for the table, the caption, if used, and the tds.  In jsp page after the creation of the table you’ll see something like that<%-- one-to-many --%> one-to-many     Some new  HTML5 stylish. We put a canvas in place of the header of the table and   we draw a text with a gradient as style. Wath to notice ? Some line of code can change strongly  the look of our web app.
back
Let’s introduce the business requirements for this part of the tutorial.  We want create items for the users. For sake of semplicity, we fixed the user id  to 1, so every new tem will be associated to the user with id: 1.  We want all new items be stored in the session. We want all new items be made by means of ajax calls. We want all new made items be saved by calling a submit for the current form. We want, after the form submit, have clean the chunk of session relative to our array of items. POM modifies. We need to modify the POM to earn the support of the servlet-api; we need it to manage the session.     javax.servlet   servlet-api   2.5 Also we add the support to mockito. We need it in the future to enhance the test phase.      org.mockito     mockito-core     1.9.5     test Jsp page.  In the jsp page we’ll introduce a new table, despite the blasphemy screams of the modern web page designers, that manages the fields necessary to create a new item. As already said the id of user will be fixed to 1, the id of the item will be undefined, because it will have a value when we persist it to the db, and the other three fields will be typed by the user. When the  “create item” button is pressed an ajax call to the SecondController class will be sent. Actually the onclick is mapped to a javascript function, that after wrapping  the data as JSON object, makes the ajax call. If all went ok the input box to the right of “create item” button will show “saved”  otherwise, if an error occurred, “NOT saved”. When all items has been made, pressing “save all items” button all items will be persisted to the db. This button performs a form submit, calling a method of  SecondController; at the end the “/“ is called and the our session variable will be cleaned or reinitialised. function ajax_create_item(json_data) {     $.ajax({           url: "action_create_item",           data: JSON.stringify(json_data),         type: "POST",         beforeSend: function(xhr) {               xhr.setRequestHeader("Accept", "application/json");               xhr.setRequestHeader("Content-Type", "application/json");           }})         .done(function(data) {           //alert(data["return"]);         $("#id_result").val("saved");         }).fail(function(data) {           $("#id_result").val("NOT saved");         });   } function create_item() { var _json_data = {"system_id" : $("#system_id").val(),            "system_description" : $("#system_description").val(),           "system_configuration" : $("#system_configuration").val()}; //alert($("#system_id").val()         + " -- " + //$("#system_description").val()    + " -- " + //$("#system_configuration").val()  ); $("#id_result").val("---"); ajax_create_item(_json_data); } SecondController. Let’s examine the our new controller. SecondController was made to cover other business requirements and for that it has been made other than HomeController. In detail it contains only two methods, the first to create user’s items and the other to persist all data to the database.The action_create_item, the responder to ajax call,  by means of JSONObject retrieves information about every item to be created, makes a new instance of ItemEntity and after save it to the HashSet in the Session.When the “/“ of the site is called (HomeController), you can see  request.setAttribute("sessionObject_1", new HashSet(), WebRequest.SCOPE_SESSION);  In this manner we reset all preceding data from the session and allocate a new HashSet to store the new possible items.The save_all_items is called when the submit of the form is pressed; here we persist the item array retrieved from the session; through service_1 we call UserDAO that implements the persistence.
Now it’s time to see persistence section. We need to add the relation between user and item. We make this by adding the following annotations in the UserEntity:  @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY, orphanRemoval = true)  @JoinColumn(name="id_user")  private Set items; The relation is one to many between user and items. With @JoinColumn(name="id_user”) we tell wich is the column on the item table that will map the primary key on the user table.  At the end, we thinlk it’s a good thing to mention the spring scopes for instantiation.  1. singleton scope singleton is the default scope. Singleton design pattern requires no introduction as it is the easiest of all to understand. In the bean definition if the scope is not given, then by default singleton scope is assumed. In a given Spring container a singleton scoped bean will be instantiated only once and the same will be used for its lifetime. 2. prototype scope prototype scope allows the bean to be instantiated whenever it is requested. Every time a separate instance is created, just opposite to singleton. Stateful beans which hold the conversational state should be declared as prototype scope. 3. request scope Spring bean configured as request scope instantiates the bean for a single HTTP request. The instantiated object lives through the HTTP request. This is available only for web-aware spring application context. 4. session scope session scope is very similar to HttpSession scope. Beans instantiated based on session scope scope lives through the HTTP session. Similar to request scope, it is applicable only for web aware spring application contexts. 5. global_session scope global_session scope is equal as session scope on portlet-based web applications. This scope is also applicable only for web aware spring application contexts. If this is global_session is used in normal web application (not in portlet), then it will behave as session scope and there will not be any error. That’s all.
Spring_Hibernate_Maven_4.zip
Download section.