Spring Mvc With Hibernate Example Apr 2026

@Controller @RequestMapping("/users") public class UserController {

@NotEmpty(message = "Name cannot be empty") @Size(min = 2, max = 50, message = "Name must be between 2 and 50 characters") @Column(name = "name", nullable = false) private String name;

@Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebConfig.class}; }

public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } spring mvc with hibernate example

<!-- JSTL --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency>

@Override public User getUserById(Long id) { Session session = sessionFactory.getCurrentSession(); return session.get(User.class, id); }

<!-- Hibernate Core --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.6.15.Final</version> </dependency> max = 50

@Autowired private UserDAO userDAO;

public int getAge() { return age; } public void setAge(int age) { this.age = age; } } UserDAO Interface package com.example.dao; import com.example.model.User; import java.util.List;

@NotEmpty(message = "Email cannot be empty") @Email(message = "Invalid email format") @Column(name = "email", unique = true, nullable = false) private String email; nullable = false) private String name

@Override public User getUserById(Long id) { return userDAO.getUserById(id); }

@Override public void deleteUser(Long id) { userDAO.deleteUser(id); } } UserController.java package com.example.controller; import com.example.model.User; import com.example.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List;

@Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/userdb?useSSL=false"); dataSource.setUsername("root"); dataSource.setPassword("password"); return dataSource; }

@Override protected Class<?>[] getRootConfigClasses() { return new Class[]{RootConfig.class}; }

@PostMapping("/save") public String saveUser(@Valid @ModelAttribute("user") User user, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return "user-form"; } userService.saveUser(user); return "redirect:/users/list"; }