Hibernate Tutorial

Core Hibernate

Hibernate Mapping

Hibernate Annotations

Hibernate with Spring Framework

Hibernate with Database

Hibernate Log4j

Inheritance Mapping

How to Create a Project using Spring MVC and Hibernate 5?

Creating a project using Spring MVC and Hibernate 5 involves several steps, from setting up the project structure, configuring Hibernate and Spring, to writing the actual business logic. In this tutorial, we'll walk through the essential steps to set up a basic Spring MVC and Hibernate 5 project.

1. Setting Up the Maven Project:

  1. Create a new Maven project using your favorite IDE or the Maven archetype.
  2. Add necessary dependencies in your pom.xml:
  • Spring Web MVC
  • Spring ORM
  • Hibernate
  • Database connector (e.g., MySQL)

2. Maven Dependencies (pom.xml):

<!-- Spring Web MVC -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.x.x.RELEASE</version>
</dependency>

<!-- Spring ORM -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>5.x.x.RELEASE</version>
</dependency>

<!-- Hibernate Core -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.x.x.Final</version>
</dependency>

<!-- MySQL Connector -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.x</version>
</dependency>

<!-- JSTL for JSP -->
<dependency>
    <groupId>javax.servlet.jsp.jstl</groupId>
    <artifactId>javax.servlet.jsp.jstl-api</artifactId>
    <version>1.2.1</version>
</dependency>
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

<!-- Servlet API and JSP API for provided scope -->
<!-- ... -->

3. Hibernate Configuration (hibernate.cfg.xml):

Place this in the src/main/resources directory:

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- JDBC connection settings -->
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>
        <property name="hibernate.connection.username">YOUR_USERNAME</property>
        <property name="hibernate.connection.password">YOUR_PASSWORD</property>

        <!-- Specify dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="hibernate.show_sql">true</property>

        <!-- Mention annotated class -->
        <!-- <mapping class="com.example.YourEntityClass"/> -->
    </session-factory>
</hibernate-configuration>

4. Spring Configuration (spring-config.xml):

Place this XML in WEB-INF:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Configure Spring MVC Dispatcher Servlet -->
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- Hibernate SessionFactory -->
    <bean id="mySessionFactory"
          class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="configLocation" value="classpath:hibernate.cfg.xml" />
    </bean>

    <!-- Transaction Manager -->
    <bean id="myTransactionManager"
          class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="mySessionFactory" />
    </bean>
</beans>

5. Configure web.xml:

Add configurations for the Spring Dispatcher Servlet and context loader listener.

6. Entity, DAO, Service Layer:

  1. Create your entity classes with Hibernate annotations.
  2. Create DAO (Data Access Object) classes to interact with the database using Hibernate.
  3. Create a Service layer, which will interact with the DAO and provide data to the Controller.

7. MVC Controller:

Use @Controller annotation to create controllers, which will handle incoming requests, interact with the Service layer, and return appropriate views.

8. JSP Views:

Create your JSP files under /WEB-INF/views/ (or as configured in the spring-config.xml).

9. Running:

Deploy your application on a servlet container (e.g., Apache Tomcat) and access the web application.

Conclusion:

Integrating Spring MVC with Hibernate offers a powerful combination for building robust, scalable web applications. This setup provides a clear separation of concerns, making it easier to maintain and scale. Remember, the versions of libraries might change, so always refer to the official documentation or Maven Central for the latest versions when setting up your project.

  1. Configuring Spring MVC and Hibernate 5 in a web application:

    • Set up the project by configuring Spring MVC and Hibernate.
    • Configure the DispatcherServlet in the web.xml file.
    • Example:
    <!-- web.xml -->
    <web-app>
        <servlet>
            <servlet-name>dispatcher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>/WEB-INF/spring-mvc-config.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>dispatcher</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    </web-app>
    
    <!-- spring-mvc-config.xml -->
    <beans>
        <!-- Configure Spring MVC and Hibernate here -->
    </beans>
    
  2. Setting up a CRUD project using Spring MVC and Hibernate 5:

    • Create a CRUD project using Spring MVC and Hibernate.
    • Define entity classes, DAOs, services, and controllers for CRUD operations.
    • Example:
    // Entity class
    @Entity
    public class Product {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
    
        // Other fields and methods
    }
    
    // DAO interface
    public interface ProductDAO {
        void save(Product product);
        Product getById(Long id);
        List<Product> getAll();
        void update(Product product);
        void delete(Long id);
    }
    
    // Service interface
    public interface ProductService {
        void save(Product product);
        Product getById(Long id);
        List<Product> getAll();
        void update(Product product);
        void delete(Long id);
    }
    
    // Controller
    @Controller
    public class ProductController {
        @Autowired
        private ProductService productService;
    
        // CRUD operations
    }
    
  3. Hibernate 5 and Spring MVC example with annotations:

    • Use annotations for configuring Hibernate 5 and Spring MVC.
    • Example:
    // Configuration class
    @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages = "com.example")
    public class AppConfig {
        // Configure beans here
    }
    
    // Hibernate Configuration class
    @Configuration
    @EnableTransactionManagement
    @PropertySource("classpath:hibernate.properties")
    public class HibernateConfig {
        // Configure Hibernate beans here
    }
    
  4. Integrating Hibernate 5 with Spring MVC controllers:

    • Integrate Hibernate 5 with Spring MVC controllers by injecting the service layer.
    • Example:
    // Controller
    @Controller
    public class ProductController {
        @Autowired
        private ProductService productService;
    
        // Use productService for CRUD operations
    }
    
  5. Creating a RESTful web service with Spring MVC and Hibernate 5:

    • Develop a RESTful web service using Spring MVC and Hibernate 5.
    • Use @RestController for the controller class.
    • Example:
    // REST Controller
    @RestController
    @RequestMapping("/api/products")
    public class ProductRestController {
        @Autowired
        private ProductService productService;
    
        // RESTful endpoints
    }
    
  6. Handling transactions in a Spring MVC and Hibernate 5 project:

    • Manage transactions by using @Transactional annotation.
    • Ensure that the TransactionManager bean is configured.
    • Example:
    // Service class
    @Service
    @Transactional
    public class ProductServiceImpl implements ProductService {
        @Autowired
        private ProductDAO productDAO;
    
        // Transactional methods
    }
    
    // Hibernate Configuration class
    @Configuration
    @EnableTransactionManagement
    @PropertySource("classpath:hibernate.properties")
    public class HibernateConfig {
        @Bean
        public HibernateTransactionManager transactionManager(EntityManagerFactory emf) {
            HibernateTransactionManager transactionManager = new HibernateTransactionManager();
            transactionManager.setEntityManagerFactory(emf);
            return transactionManager;
        }
    }
    
  7. Hibernate 5 and Spring MVC project with Maven setup:

    • Set up a Maven project for a Spring MVC and Hibernate 5 web application.
    • Include dependencies for Spring MVC, Hibernate, and other required libraries.
    • Example:
    <!-- pom.xml -->
    <dependencies>
        <!-- Spring MVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.12.RELEASE</version>
        </dependency>
    
        <!-- Hibernate 5 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.5.6.Final</version>
        </dependency>
    
        <!-- Other dependencies -->
    </dependencies>
    
    • Organize your project structure, and Maven will automatically download the dependencies.