CRUD operations Tutorial using Java Spring, Hibernate and MySQL

[15864 views]




This tutorial aims at creating a Dynamic Web Application using Java Spring which implements CRUD(Create - Read - Update - Delete) operations in MySQL database through hibernate.

We will use the following for this tutorial:
  • Netbeans 8.0 IDE
  • Apache Tomcat 8 ( Version 9 work with netbeans V8.2+)
  • MySQL
  • Spring
  • Hibernate 4

Setting up the database:

Create table student in database tutorial in MySql:

create database tutorial; use tutorial; create table student( roll int primary key, name varchar(30) not null, school varchar(30) not null );

Setting up project in Netbeans:

  1. Create a new project under web application and name it "webApplication".
    new project under web application in Spring Project CRUD operations Tutorial with Hibernate and mysql

  2. Under Server selection, select Apache Tomcat 8.
    Apache Tomcat 8 in Spring Project CRUD operations Tutorial with Hibernate and mysql

  3. Under Frameworks, select Spring and Hibernate.
    select Spring and Hibernate in Spring Project CRUD operations Tutorial with Hibernate and mysql

When you create new project, web.xml file is generated in WEB-INF folder. When application starts, web.xml loads and scans entire file. Edit this file add homepage "redirect.jsp" servlet named "spring" servlet "spring" mapping with url-pattern "/"
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <welcome-file-list> <welcome-file>redirect.jsp</welcome-file> </welcome-file-list> <display-name>Spring-Hibernate</display-name> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>

We have named "spring" servlet in web.xml file, so we need to create this file and add Spring and Hibernate configurations in it. Since the name is spring, servlet name will be "spring-servlet.xml"

This xml file contains base package location(com.tutorial), MVC view resolver, DataSource definition, Hibernate session factory and Hibernate transaction manager.

Place the following credentials in datasource bean:

driverName = com.mysql.jdbc.Driver databaseurl = jdbc:mysql://localhost/tutorial username = <your database username> password = <your database password>
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.tutorial" /> <mvc:annotation-driven /> <beans:bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <beans:property name="prefix" value="/WEB-INF/jsp/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> <beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" /> <beans:property name="url" value="jdbc:mysql://localhost/tutorial" /> <beans:property name="username" value="username" /> <beans:property name="password" value="password" /> </beans:bean> <beans:bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <beans:property name="dataSource" ref="dataSource" /> <beans:property name="packagesToScan" value="com.tutorial.entity" /> <beans:property name="hibernateProperties"> <beans:props> <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQSDialect</beans:prop> </beans:props> </beans:property> </beans:bean> <beans:bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <beans:property name="sessionFactory" ref="sessionFactory" /> </beans:bean> <tx:annotation-driven transaction-manager="transactionManager" /> </beans:beans>

"" in above servlet code means that the project will be annotation driven. Hibernate will search for annotations in the project.

Now under com.tutorial, create an entity package. Under this package, create Student.java class file which acts as an entity.

Student.java

package com.tutorial.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "student") public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "roll") private Integer roll; @Column(name = "name") private String name; @Column(name = "school") private String school; public Integer getRoll() { return roll; } public void setRoll(Integer roll) { this.roll = roll; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } } }

@Table denotes table with name = student
@Id denotes field with Primary Key
@Column denotes a field in the table

Now we need to create a Data Access Object named StudentDAO.java which will be placed in com.tutorial.dao package. This class will contain an interface for adding student, searching and removing student with id, viewing all students.

StudentDAO.java

package com.tutorial.dao; import com.tutorial.entity.Student; public interface StudentDAO{ public void saveStudentObj(Student obj); public List<Student> getAllStudents(); public Student getStudentObj(int id); public void removeStudentObj(int id);

To make our code modular, we will write the above method's implementation in another file StudentDAOImplementation.java.
@Repository annotation means that this file acts as the database of the application.

StudentDAOImplementation.java

package com.tutorial.dao; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.tutorial.entity.Student; @Repository public class StudentDAOImplementation implements StudentDAO { @Autowired SessionFactory sessionFactory; @Override public void saveStudentObj(Student studentObj) { sessionFactory.getCurrentSession().saveOrUpdate(studentObj); } @Override public List<Student> getAllStudents() { Session currentSession = sessionFactory.getCurrentSession(); List<Student> theQuery = currentSession.createQuery("from Student").list(); return theQuery; } @Override public Student getStudentObj(int id) { Student studentObj = (Student) sessionFactory.getCurrentSession().get(Student.class, id); return studentObj; } @Override public void removeStudentObj(int id) { Student studentObj = (Student) sessionFactory.getCurrentSession().get(Student.class, id); sessionFactory.getCurrentSession().delete(studentObj); }

Now lets create services for

                 



Clear Any Java Interview by Reading our Ebook Once.


Can you clear Java Interview?



Comments










Search

Hot Deals ends in













Technical Quizzes Specially For You:

Games:
     



Search Tags

    simple tutorial explaining crud operations using java spring framework

    java spring hibernate and mysql tutorial