Spring 4 MVC with Hibernate 4 & MySQL Integration Example (annotation based) to create a CRUD oriented web application, making use of AOP based transactions. Huawei’s AR2200 Series Enterprise Routers provide flexible, scalable, and secure switching and routing for converged wired and wireless 3G LTE networks. Cisco has confirmed that the following products are not vulnerable to the six distinct vulnerabilities announced by the OpenSSL Project on June 11, 2015. Spring 4 MVC+Hibernate 4+My. SQL+Maven integration example using annotations. In this tutorial , we will integrate Spring with Hibernate using annotation based configuration. We will develop a simple CRUD oriented web application containing a form asking user input, saving that input in My. SQL database using Hibernate , retrieving the records from database and updating or deleting them within transaction, all using annotation configuration. Testing part of this post is covered in detail in Next Post where we perform unit/integration test using Test. NG, mockito, spring- test, DBUnit & H2 database. To know more about testing with Test.
NG in general, please refer our Test. NG Tutorials. Let’s get started. Following technologies being used: Spring 4. RELEASEHibernate Core 4. Finalvalidation- api 1. Finalhibernate- validator 5. Final. My. SQL Server 5. Maven 3. JDK 1. 7. Tomcat 8. 0. 2. 1Eclipse JUNO Service Release 2. Test. NG 6. 9. 4. Mockito 1. 1. 0. 1. DBUnit 2. 2. H2 Database 1. Let’s begin. Step 1: Create the directory structure. Following will be the final project structure: Let’s now add the content mentioned in above structure explaining each in detail. Step 2: Update pom. As we are using full annotation configuration, we don’t even include web. Since in this example we will use a form to accept input from user, we need also to validate the user input. We will choose JSR3. Validation here, so we have included validation- api which represents the specification, and hibernate- validator which represents an implementation of this specification. In general, containers might already contains these libraries, so we can set the scope as . Testing part of this post is described in detail in Next post. Rest of the dependencies are for Spring, Hibernate and Joda- Time. Step 3: Configure Hibernatecom. Hibernate. Configuration. Properties. import javax. Data. Source. import org. Session. Factory. Autowired. import org. Bean. import org. Component. Scan. import org. Configuration. import org. Property. Source. Environment. import org. Driver. Manager. Data. Source. import org. Hibernate. Transaction. Manager. import org. Local. Session. Factory. Bean. import org. Enable. Transaction. Management. @Enable. Transaction. Management. Component. Scan(. In our case, this class represent hibernate configuration.@Component. Scan is equivalent to context: component- scan base- package=. Thanks to @Property. Source, we can externalize the real values in a . Spring’s Environment to fetch the value corresponding to an item. Once the Session. Factory is created, it will be injected into Bean method transaction. Manager which may eventually provide transaction support for the sessions created by this session. Factory. Below is the properties file used in this post./src/main/resources/application. Class. Name = com. Driver. jdbc. url = jdbc: mysql: //localhost: 3. My. SQLDialect. hibernate. In case of validation failure, default error messages are shown. To override those default by your own custom . Method message. Source is there for same purpose. Notice the parameter provided (messages) to basename method. Spring will search for a file named messages. Let’s add that file: /src/main/resources/messages. Size. employee. name=Name must be between . Please fill in different value. It also validates the user input. Request. Mapping(value = . It also validates the user input. Request. Mapping(value = . Method list. Employees , annotated with @Request. Method. GET, handling both the default URL . It acts as handle for initial page of application, showing a list of existing employees. Method new. Employee is handling the GET request for the new employee registration page, showing page backed by a model Employee object. Method save. Employee is annotated with @Request. Method. POST, and will handle the form- submission POST requests for new employee registration (. Notice the parameters and their orders in this method. Binding. Result contains the outcome of this validation and any error that might have occurred during this validation. Notice that Binding. Result must come right after the validated object else spring won’t be able to validate and an exception been thrown. In case of validation failure, custom error messages(as we have configured in step 4) are shown. We have also included code to check for SSN uniqueness as it is declared to be unique in database. Before saving/updating an employee, we are checking if the SSN is unique. If not, we generate validation error and redirect to registration page. This peace of code demonstrate a way tofill it custom errors outside the validation framework as well while still using internationalized messages. Method edit. Employee takes you to registration page with employee details filled in, while update. Employee gets called when you click on update button after possible updation on gui. Method delete. Employee is handling the deletion of an employee by it’s SSN number. Notice @Path. Variable , which indicates that this parameter will be bound to variable in URI template (SSN in our case). As for as Annotation based configuration goes,this is all we need to do. Now to make the application complete, we will add service layer, dao layer, views, Domain object, sample database schema and run the application. Step 7: Add DAO Layercom. Abstract. Dao. package com. Serializable. import java. Parameterized. Type. Criteria. import org. Session. import org. Session. Factory. Autowired. public abstract class Abstract. Dao< PK extends Serializable, T> . It provides the wrapper methods for common hibernate operations. Notice above, that Session. Factory we have created earlier in step 3, will be autowired here. Note that since the transaction are on method scope, and inside method we are using DAO, DAO method will be executed within same transaction. Step 9: Create Domain Entity Class(POJO)Let’s create the actual Employee Entity itself whose instances we will be playing with in database. Employee. package com. Big. Decimal. import javax. Column. import javax. Entity. import javax. Generated. Value. Generation. Type. Id. import javax. Table. import javax. Digits. import javax. Not. Null. import javax. Size. import org. Type. import org. Not. Empty. import org. Local. Date. import org. Date. Time. Format. Table(name=? 0 : ssn. Code()). return result. Deploy the war to a Servlet 3. Since here i am using Tomcat, i will simply put this war file into tomcat webapps folder and click on start. If you prefer to deploy from within Eclipse using tomcat: For those of us, who prefer to deploy and run from within eclipse, and might be facing difficulties setting Eclipse with tomcat, the detailed step- by- step solution can be found at : How to setup tomcat with Eclipse. Open browser and browse at http: //localhost: 8. Spring. Hibernate. Example/Now click on “Add New Employee”, and click on Register button wihtout filling any detail: Now fill the details Click on Register, you should get something similar to: Click on list to go to listing: Now add few records as before: Now click on delete link of Second record, it should get deleted. Now click on SSN link (which is an update) of 2nd record to update it: Now edit some fields, in addition change the SSN value to a value for an existing record: Try to update, you should get validation error on SSN: Fix that error by changing SSN to unique value, update, and then view complete list of records, update changes should be taken into account: Finally check the database at this moment : That’s it. In the Next post, we will tests this application thoroughly with unit & integration tests, using Test. NG, Mockito, DBUnit and testing best practices. Download Source Code. References. If you like tutorials on this site, why not take a step further and connect me on Facebook , Google Plus & Twitter as well?
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
August 2017
Categories |