Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3366b6e

Browse files
add Spring MVC Hibernate Mysql integration CRUD Example
0 parents commit 3366b6e

File tree

16 files changed

+819
-0
lines changed

16 files changed

+819
-0
lines changed

‎pom.xml‎

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
<?xml version="1.0"?>
2+
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
3+
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
4+
5+
<modelVersion>4.0.0</modelVersion>
6+
<groupId>com.javabycode.springmvc</groupId>
7+
<artifactId>SpringMVCHibernateExample</artifactId>
8+
<packaging>war</packaging>
9+
<name>SpringMVCHibernateExample</name>
10+
<version>1.0</version>
11+
12+
<properties>
13+
<springframework.version>4.3.0.RELEASE</springframework.version>
14+
<hibernate.version>4.3.6.Final</hibernate.version>
15+
<mysql.version>5.1.31</mysql.version>
16+
<joda-time.version>2.3</joda-time.version>
17+
</properties>
18+
19+
<dependencies>
20+
<!-- Spring -->
21+
<dependency>
22+
<groupId>org.springframework</groupId>
23+
<artifactId>spring-core</artifactId>
24+
<version>${springframework.version}</version>
25+
</dependency>
26+
<dependency>
27+
<groupId>org.springframework</groupId>
28+
<artifactId>spring-web</artifactId>
29+
<version>${springframework.version}</version>
30+
</dependency>
31+
<dependency>
32+
<groupId>org.springframework</groupId>
33+
<artifactId>spring-webmvc</artifactId>
34+
<version>${springframework.version}</version>
35+
</dependency>
36+
<dependency>
37+
<groupId>org.springframework</groupId>
38+
<artifactId>spring-tx</artifactId>
39+
<version>${springframework.version}</version>
40+
</dependency>
41+
<dependency>
42+
<groupId>org.springframework</groupId>
43+
<artifactId>spring-orm</artifactId>
44+
<version>${springframework.version}</version>
45+
</dependency>
46+
47+
<!-- Hibernate -->
48+
<dependency>
49+
<groupId>org.hibernate</groupId>
50+
<artifactId>hibernate-core</artifactId>
51+
<version>${hibernate.version}</version>
52+
</dependency>
53+
54+
<!-- jsr303 validation -->
55+
<dependency>
56+
<groupId>javax.validation</groupId>
57+
<artifactId>validation-api</artifactId>
58+
<version>1.1.0.Final</version>
59+
</dependency>
60+
<dependency>
61+
<groupId>org.hibernate</groupId>
62+
<artifactId>hibernate-validator</artifactId>
63+
<version>5.1.3.Final</version>
64+
</dependency>
65+
66+
<!-- MySQL -->
67+
<dependency>
68+
<groupId>mysql</groupId>
69+
<artifactId>mysql-connector-java</artifactId>
70+
<version>${mysql.version}</version>
71+
</dependency>
72+
73+
<!-- Joda-Time -->
74+
<dependency>
75+
<groupId>joda-time</groupId>
76+
<artifactId>joda-time</artifactId>
77+
<version>${joda-time.version}</version>
78+
</dependency>
79+
80+
<!-- To map JodaTime with database type -->
81+
<dependency>
82+
<groupId>org.jadira.usertype</groupId>
83+
<artifactId>usertype.core</artifactId>
84+
<version>3.0.0.CR1</version>
85+
</dependency>
86+
87+
<!-- Servlet+JSP+JSTL -->
88+
<dependency>
89+
<groupId>javax.servlet</groupId>
90+
<artifactId>javax.servlet-api</artifactId>
91+
<version>3.1.0</version>
92+
</dependency>
93+
<dependency>
94+
<groupId>javax.servlet.jsp</groupId>
95+
<artifactId>javax.servlet.jsp-api</artifactId>
96+
<version>2.3.1</version>
97+
</dependency>
98+
<dependency>
99+
<groupId>javax.servlet</groupId>
100+
<artifactId>jstl</artifactId>
101+
<version>1.2</version>
102+
</dependency>
103+
104+
</dependencies>
105+
106+
107+
<build>
108+
<finalName>spring-mvc-hibernate-example</finalName>
109+
<plugins>
110+
<plugin>
111+
<artifactId>maven-compiler-plugin</artifactId>
112+
<version>3.5.1</version>
113+
<configuration>
114+
<source>1.7</source>
115+
<target>1.7</target>
116+
</configuration>
117+
</plugin>
118+
<plugin>
119+
<artifactId>maven-war-plugin</artifactId>
120+
<version>2.6</version>
121+
<configuration>
122+
<failOnMissingWebXml>false</failOnMissingWebXml>
123+
</configuration>
124+
</plugin>
125+
</plugins>
126+
</build>
127+
</project>
128+
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.javabycode.springmvc.configuration;
2+
3+
import java.util.Properties;
4+
5+
import javax.sql.DataSource;
6+
7+
import org.hibernate.SessionFactory;
8+
import org.springframework.beans.factory.annotation.Autowired;
9+
import org.springframework.context.annotation.Bean;
10+
import org.springframework.context.annotation.ComponentScan;
11+
import org.springframework.context.annotation.Configuration;
12+
import org.springframework.context.annotation.PropertySource;
13+
import org.springframework.core.env.Environment;
14+
import org.springframework.jdbc.datasource.DriverManagerDataSource;
15+
import org.springframework.orm.hibernate4.HibernateTransactionManager;
16+
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
17+
import org.springframework.transaction.annotation.EnableTransactionManagement;
18+
19+
@Configuration
20+
@EnableTransactionManagement
21+
@ComponentScan({ "com.javabycode.springmvc.configuration" })
22+
@PropertySource(value = { "classpath:jdbc.properties" })
23+
public class MyHibernateConfig {
24+
25+
@Autowired
26+
private Environment environment;
27+
28+
@Bean
29+
public LocalSessionFactoryBean sessionFactory() {
30+
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
31+
sessionFactory.setDataSource(dataSource());
32+
sessionFactory.setPackagesToScan(new String[] { "com.javabycode.springmvc.model" });
33+
sessionFactory.setHibernateProperties(hibernateProperties());
34+
return sessionFactory;
35+
}
36+
37+
@Bean
38+
public DataSource dataSource() {
39+
DriverManagerDataSource dataSource = new DriverManagerDataSource();
40+
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
41+
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
42+
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
43+
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
44+
return dataSource;
45+
}
46+
47+
private Properties hibernateProperties() {
48+
Properties properties = new Properties();
49+
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
50+
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
51+
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
52+
return properties;
53+
}
54+
55+
@Bean
56+
@Autowired
57+
public HibernateTransactionManager transactionManager(SessionFactory s) {
58+
HibernateTransactionManager txManager = new HibernateTransactionManager();
59+
txManager.setSessionFactory(s);
60+
return txManager;
61+
}
62+
}
63+
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.javabycode.springmvc.configuration;
2+
3+
import org.springframework.context.MessageSource;
4+
import org.springframework.context.annotation.Bean;
5+
import org.springframework.context.annotation.ComponentScan;
6+
import org.springframework.context.annotation.Configuration;
7+
import org.springframework.context.support.ResourceBundleMessageSource;
8+
import org.springframework.web.servlet.ViewResolver;
9+
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
10+
import org.springframework.web.servlet.view.InternalResourceViewResolver;
11+
import org.springframework.web.servlet.view.JstlView;
12+
13+
@Configuration
14+
@EnableWebMvc
15+
@ComponentScan(basePackages = "com.javabycode.springmvc")
16+
public class MyWebConfig {
17+
18+
@Bean
19+
public ViewResolver viewResolver() {
20+
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
21+
viewResolver.setViewClass(JstlView.class);
22+
viewResolver.setPrefix("/WEB-INF/views/");
23+
viewResolver.setSuffix(".jsp");
24+
25+
return viewResolver;
26+
}
27+
28+
@Bean
29+
public MessageSource messageSource() {
30+
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
31+
messageSource.setBasename("messages");
32+
return messageSource;
33+
}
34+
}
35+
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.javabycode.springmvc.configuration;
2+
3+
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
4+
5+
public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
6+
7+
@Override
8+
protected Class<?>[] getServletConfigClasses() {
9+
return new Class[] { MyWebConfig.class };
10+
}
11+
12+
@Override
13+
protected String[] getServletMappings() {
14+
return new String[] { "/" };
15+
}
16+
17+
@Override
18+
protected Class<?>[] getRootConfigClasses() {
19+
return null;
20+
}
21+
22+
}
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
package com.javabycode.springmvc.controller;
2+
3+
import java.util.List;
4+
import java.util.Locale;
5+
6+
import javax.validation.Valid;
7+
8+
import org.springframework.beans.factory.annotation.Autowired;
9+
import org.springframework.context.MessageSource;
10+
import org.springframework.stereotype.Controller;
11+
import org.springframework.ui.ModelMap;
12+
import org.springframework.validation.BindingResult;
13+
import org.springframework.validation.FieldError;
14+
import org.springframework.web.bind.annotation.PathVariable;
15+
import org.springframework.web.bind.annotation.RequestMapping;
16+
import org.springframework.web.bind.annotation.RequestMethod;
17+
18+
import com.javabycode.springmvc.model.Student;
19+
import com.javabycode.springmvc.service.StudentService;
20+
21+
@Controller
22+
@RequestMapping("/")
23+
public class MyController {
24+
25+
@Autowired
26+
StudentService service;
27+
28+
@Autowired
29+
MessageSource messageSource;
30+
31+
/*
32+
* List all existing Students.
33+
*/
34+
@RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
35+
public String listStudents(ModelMap model) {
36+
37+
List<Student> students = service.findAllStudents();
38+
model.addAttribute("students", students);
39+
return "allstudents";
40+
}
41+
42+
/*
43+
* Add a new Student.
44+
*/
45+
@RequestMapping(value = { "/new" }, method = RequestMethod.GET)
46+
public String newStudent(ModelMap model) {
47+
Student student = new Student();
48+
model.addAttribute("student", student);
49+
model.addAttribute("edit", false);
50+
return "registration";
51+
}
52+
53+
/*
54+
* Handling POST request for validating the user input and saving Student in database.
55+
*/
56+
@RequestMapping(value = { "/new" }, method = RequestMethod.POST)
57+
public String saveStudent(@Valid Student student, BindingResult result,
58+
ModelMap model) {
59+
60+
if (result.hasErrors()) {
61+
return "registration";
62+
}
63+
64+
if(!service.isStudentCodeUnique(student.getId(), student.getCode())){
65+
FieldError codeError =new FieldError("Student","code",messageSource.getMessage("non.unique.code", new String[]{student.getCode()}, Locale.getDefault()));
66+
result.addError(codeError);
67+
return "registration";
68+
}
69+
70+
service.saveStudent(student);
71+
72+
model.addAttribute("success", "Student " + student.getName() + " registered successfully");
73+
return "success";
74+
}
75+
76+
77+
/*
78+
* Provide the existing Student for updating.
79+
*/
80+
@RequestMapping(value = { "/edit-{code}-student" }, method = RequestMethod.GET)
81+
public String editStudent(@PathVariable String code, ModelMap model) {
82+
Student student = service.findStudentByCode(code);
83+
model.addAttribute("student", student);
84+
model.addAttribute("edit", true);
85+
return "registration";
86+
}
87+
88+
/*
89+
* Handling POST request for validating the user input and updating Student in database.
90+
*/
91+
@RequestMapping(value = { "/edit-{code}-student" }, method = RequestMethod.POST)
92+
public String updateStudent(@Valid Student student, BindingResult result,
93+
ModelMap model, @PathVariable String code) {
94+
95+
if (result.hasErrors()) {
96+
return "registration";
97+
}
98+
99+
if(!service.isStudentCodeUnique(student.getId(), student.getCode())){
100+
FieldError codeError =new FieldError("Student","code",messageSource.getMessage("non.unique.code", new String[]{student.getCode()}, Locale.getDefault()));
101+
result.addError(codeError);
102+
return "registration";
103+
}
104+
105+
service.updateStudent(student);
106+
107+
model.addAttribute("success", "Student " + student.getName() + " updated successfully");
108+
return "success";
109+
}
110+
111+
112+
/*
113+
* Delete an Student by it's CODE value.
114+
*/
115+
@RequestMapping(value = { "/delete-{code}-student" }, method = RequestMethod.GET)
116+
public String deleteStudent(@PathVariable String code) {
117+
service.deleteStudentByCode(code);
118+
return "redirect:/list";
119+
}
120+
121+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /