Spring5 MVC Hibernate Demo

Spring MVC and Hibernate CRUD Example

In this Spring MVC and Hibernate annotation example, learn the following concepts:

  • Create a Spring MVC web application from scratch
  • Handle form submission
  • Integrate hibernate to connect to the H2 database
  • Add hibernate validator for input form fields validation

We will create a simple application where we can create user information (name and email). The user details will be first validated and then stored in H2 database using hibernate. Another page will list all stored users in the database.

The class diagram of the application is as follows. It lists all the important classes, methods and interactions between them.

Class Diagram

Start with adding the latest version of spring-webmvc, spring-orm, hibernate-core, hibernate-validator, jakarta.persistence-api and jakarta.servlet-api dependencies. Note that we are using Spring Framework 6 so the baseline Java version is Java 17.

 17 false 6.0.6 6.2.2.Final 8.0.0.Final 0.9.5.5 3.1.0 3.1.0 2.1.214    org.springframework spring-webmvc $ jakarta.servlet jakarta.servlet-api $ provided   org.springframework spring-orm $ jakarta.persistence jakarta.persistence-api $ org.hibernate.orm hibernate-core $  org.hibernate.orm hibernate-c3p0 $  org.hibernate.validator hibernate-validator $  com.h2database h2 $ runtime  

Beginning with Servlet 3, it became possible to configure the Servlet Container with (almost) no XML. For this, there is the ServletContainerInitializer in the Servlet specification. In this class, we can register filters, listeners, servlets etc. as we would traditionally do in a web.xml .

Spring provides SpringServletContainerInitializer that knows how to handle WebApplicationInitializer classes. AbstractAnnotationConfigDispatcherServletInitializer class implements WebMvcConfigurer which internally implements WebApplicationInitializer . It registers a ContextLoaderlistener (optionally) and a DispatcherServlet and allows you to easily add configuration classes to load for both classes and to apply filters to the DispatcherServlet and provide the servlet mapping.

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer < @Override protected Class[] getRootConfigClasses() < return new Class[] < HibernateConfig.class >; > @Override protected Class[] getServletConfigClasses() < return new Class[] < WebMvcConfig.class >; > @Override protected String[] getServletMappings() < return new String[] < "/" >; > >

Spring MVC configuration using annotations is as follows.

@Configuration @EnableWebMvc @ComponentScan(basePackages = < "com.howtodoinjava.demo.spring">) public class WebMvcConfig implements WebMvcConfigurer < @Bean public InternalResourceViewResolver resolver() < InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setViewClass(JstlView.class); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); return resolver; >@Bean public MessageSource messageSource() < ResourceBundleMessageSource source = new ResourceBundleMessageSource(); source.setBasename("messages"); return source; >@Override public Validator getValidator() < LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.setValidationMessageSource(messageSource()); return validator; >>
  • WebMvcConfigurer defines options for customizing or adding to the default Spring MVC configuration enabled through the use of @EnableWebMvc .
  • @EnableWebMvc enables default Spring MVC configuration and registers Spring MVC infrastructure components expected by the DispatcherServlet .
  • @Configuration indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.
  • @ComponentScan annotation is used to specify the base packages to scan. Any class which is annotated with @Component and @Configuration will be scanned.
  • InternalResourceViewResolver helps in mapping the logical view names to view files under a certain pre-configured directory directly.
  • ResourceBundleMessageSource accesses resource bundles using specified basenames (here it is messages).
  • LocalValidatorFactoryBean bootstraps a javax.validation.ValidationFactory and exposes it through the Spring Validator interface as well as through the JSR-303 Validator interface and the ValidatorFactory interface itself.
Читайте также:  Html projects source codes

Hibernate configuration used in the example is based on hibernate Java-based configuration.

@Configuration @EnableTransactionManagement @ComponentScans(value = ) public class HibernateConfig < @Bean public LocalSessionFactoryBean getSessionFactory() < LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean(); factoryBean.setPackagesToScan("com.howtodoinjava.demo.spring.model"); factoryBean.setConfigLocation(context.getResource("classpath:hibernate.cfg.xml")); return factoryBean; >@Bean public HibernateTransactionManager getTransactionManager() < HibernateTransactionManager transactionManager = new HibernateTransactionManager(); transactionManager.setSessionFactory(getSessionFactory().getObject()); return transactionManager; >>
  • LocalSessionFactoryBean creates a Hibernate SessionFactory . This is the usual way to set up a shared Hibernate SessionFactory in a Spring application context.
  • EnableTransactionManagement enables Spring’s annotation-driven transaction management capability.
  • HibernateTransactionManager binds a Hibernate Session from the specified factory to the thread, potentially allowing for one thread-bound Session per factory. This transaction manager is appropriate for applications that use a single Hibernate SessionFactory for transactional data access, but it also supports direct DataSource access within a transaction i.e. plain JDBC.
  org.hibernate.connection.C3P0ConnectionProvider class,hbm org.hibernate.dialect.H2Dialect true org.h2.Driver sa password jdbc:h2:mem:testdb create-drop com.howtodoinjava.demo.spring.model 5 20 2 1800 150  

6. Controller and Request Mappings

The controller class has two simple REST mappings for GET and POST operations.

We have added the request body validation using hibernate validator. If input fields are not validated, then return the same form bean to display error messages. Else return refreshed view.

@Controller public class UserController < @Autowired private UserService userService; @GetMapping("/") public String userForm(Locale locale, Model model) < model.addAttribute("users", userService.list()); return "editUsers"; >@ModelAttribute("user") public User formBackingObject() < return new User(); >@PostMapping("/addUser") public String saveUser(@ModelAttribute("user") @Valid User user, BindingResult result, Model model) < if (result.hasErrors()) < model.addAttribute("users", userService.list()); return "editUsers"; >userService.save(user); return "redirect:/"; > >

Service and DAO layers are normal service components annotated with @Service and @Repository stereo-type annotations. @Transactional annotation is applied at the service layer for transaction support.

public interface UserService < void save(User user); Listlist(); > @Service public class UserServiceImp implements UserService < @Autowired private UserDao userDao; @Transactional public void save(User user) < userDao.save(user); >@Transactional(readOnly = true) public List list() < return userDao.list(); >>
public interface UserDao < void save(User user); Listlist(); > @Repository public class UserDaoImp implements UserDao < @Autowired private SessionFactory sessionFactory; @Override public void save(User user) < sessionFactory.getCurrentSession().save(user); >@Override public List list() < TypedQueryquery = sessionFactory.getCurrentSession().createQuery("from User"); return query.getResultList(); > >
@Entity @Table(name = "TBL_USERS") public class User < @Id @GeneratedValue @Column(name = "USER_ID") private Long id; @Column(name = "USER_NAME") @Size(max = 20, min = 3, message = "") @NotEmpty(message="Please Enter your name") private String name; @Column(name = "USER_EMAIL", unique = true) @Email(message = "") @NotEmpty(message="Please Enter your email") private String email; //Getters and Setters >

8. Views and Message Resources

Finally, the JSP files and messages resource bundle is given below.

        .error < color: red; >table < width: 50%; border-collapse: collapse; border-spacing: 0px; >table td 

Input Form

Name
Email

Users List

Name Email
$ $
user.name.invalid = Name must be between and characters. user.email.invalid = Please enter valid email address.

Let’s run the application using maven jetty plugin. Execute maven goal : jetty:run .

mvn cleanm install jetty:run

Initial Screen

Invalid Input Validation

Valid Form Submission

Hibernate: call next value for hibernate_sequence Hibernate: insert into TBL_USERS (USER_EMAIL, USER_NAME, USER_ID) values (?, ?, ?) Hibernate: select user0_.USER_ID as USER_ID1_0_, user0_.USER_EMAIL as USER_EMA2_0_, user0_.USER_NAME as USER_NAM3_0_ from TBL_USERS user0_

I hope that you have found this spring hibernate web application example to set you to start for developing your own application. This is primarily for beginners, yet it will help you build any Spring MVC and hibernate with annotation configuration.

Источник

Оцените статью