I’m going to create as we speak an entire Finish-to-Finish SpringMVC 3, Hibernate Three CRUD tutorial which makes use of MySQL as a database to retailer data. This will probably be a easy Bookstore software the place consumer can Create, Replace, View of Delete guide data. We are going to use Hibernate Three as an ORM instrument with Spring MVC as a MVC Framework.
On this tutorial you’ll find out how we combine SpringMVC with Hibernate utilizing JPA annotations and I will even going to make use of Spring annotation configuration for Controller, Service and Repository annotations. The primary benefit of utilizing @Repository
or @Service
over @Element
is that it’s simple to put in writing an AOP pointcut that targets, as an illustration, all lessons annotated with @Repository
.
Upon completion of this tutorial the Software will appear like following screenshot.
Lets Begin
To begin with, We’d like a SQL Desk to avoid wasting our Books particulars in RDBMS. You’ll be able to create this desk by the assistance of Hibernate additionally however its good to comply with Backside-Up method to create an Software. Following SQL used to create a Books desk in MySQL database.
1
2
3
4
5
6
7
8
|
CREATE TABLE IF NOT EXISTS books (
id int(10) NOT NULL auto_increment,
book_name varchar(100) NOT NULL,
writer varchar(100) NOT NULL,
value int(10) NOT NULL,
qty int(10) NOT NULL,
PRIMARY KEY (id)
);
|
Hibernate Entity Class: Ebook
The @Entity
annotation is used to mark this class as an Entity bean. So the category ought to atleast have a package deal scope no-argument constructor.
The @Desk
annotation is used to specify the desk to persist the info. The identify attribute refers back to the desk identify. If @Desk
annotation isn’t specified then Hibernate will by default use the category identify because the desk identify.
The @Id
annotation is used to specify the identifier property of the entity bean. The location of the @Id annotation determines the default entry technique that Hibernate will use for the mapping. If the @Id
annotation is positioned over the sector, then filed entry will probably be used. As a substitute if it positioned over the getter methodology of that discipline, then property entry will probably be used. Right here we use property entry.
The @GeneratedValue
annotation is used to specify the first key era technique to make use of. If the technique isn’t specified by default AUTO will probably be used.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
package deal org.techzoo.springmvc.kind;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Desk;
@Entity
@Desk(identify = “BOOKS”, schema = “TEST”)
public class Ebook {
@Id
@Column(identify=“ID”)
@GeneratedValue
personal Integer id;
@Column(identify=“BOOK_NAME”)
personal String bookName;
@Column(identify=“AUTHOR”)
personal String writer;
@Column(identify=“PRICE”)
personal int value;
@Column(identify=“QTY”)
personal int amount;
public Integer getId()
{return id;}
public String getBookName()
{return bookName;}
public String getAuthor()
{return writer;}
public int getPrice()
{return value;}
public int getQuantity()
{return amount;}
public void setId(Integer id)
{this.id = id;}
public void setBookName(String bookName)
{this.bookName = bookName;}
public void setAuthor(String writer)
{this.writer = writer;}
public void setPrice(int value)
{this.value = value;}
public void setQuantity(int amount)
{this.amount = amount;}
}
|
Knowledge Entry Layer
Knowledge entry layer of our software consist of 1 BookDoa Interface and its implementation BookDaoImpl class. The BookDaoImpl class has a @Repository
annotation which used to allow this class to eligible for persistence exception translation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package deal org.techzoo.springmvc.dao;
import java.util.Listing;
import org.techzoo.springmvc.kind.Ebook;
public interface BookDao {
public void addBook(Ebook guide);
public void updateBook(Ebook guide);
public Listing<Ebook> listBooks();
public Ebook getBookById(Integer bookId);
public void removeBook(Integer id);
}
|
BookDaoImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
package deal org.techzoo.springmvc.dao;
import java.util.Listing;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.manufacturing facility.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.techzoo.springmvc.kind.Ebook;
@Repository
public class BookDaoImpl implements BookDao {
@Autowired
personal SessionFactory sessionFactory;
@Override
public void addBook(Ebook guide) {
sessionFactory.getCurrentSession().save(guide);
}
@Override
public void removeBook(Integer id) {
Ebook guide = (Ebook)sessionFactory.getCurrentSession()
.load(Ebook.class, id);
if(null != guide) {
sessionFactory.getCurrentSession().delete(guide);
}
}
@Override
@SuppressWarnings(“unchecked”)
public Listing<Ebook> listBooks() {
return sessionFactory.getCurrentSession()
.createQuery(“from Ebook”).listing();
}
@Override
public void updateBook(Ebook guide) {
sessionFactory.getCurrentSession().replace(guide);
}
@Override
@SuppressWarnings(“unchecked”)
public Ebook getBookById(Integer bookId) {
Session session = sessionFactory.getCurrentSession();
Listing<Ebook> listing = session.createQuery(“from Ebook b the place b.id = :bookId”)
.setParameter(“bookId”, bookId)
.listing();
return listing.dimension() > 0 ?(Ebook)listing.get(0): null;
}
}
|
Service Layer
Service layer additionally consist of 1 Service interface BookService and its implementation class BookServiceImpl.java
. We’ve annotated BookServiceImpl class with @Service
annotation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package deal org.techzoo.springmvc.service;
import java.util.Listing;
import org.techzoo.springmvc.kind.Ebook;
public interface BookService {
public void addBook(Ebook guide);
public void updateBook(Ebook guide);
public Ebook getBookById(Integer bookId);
public Listing<Ebook> listBooks();
public void removeBook(Integer id);
}
|
BookServiceImpl.java
class…
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
package deal org.techzoo.springmvc.service;
import java.util.Listing;
import org.springframework.beans.manufacturing facility.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.techzoo.springmvc.dao.BookDao;
import org.techzoo.springmvc.kind.Ebook;
@Service
public class BookServiceImpl implements BookService {
@Autowired
personal BookDao bookDao;
@Transactional
public void addBook(Ebook guide) {
bookDao.addBook(guide);
}
@Transactional
public void removeBook(Integer id) {
bookDao.removeBook(id);
}
@Transactional
public Listing<Ebook> listBooks() {
return bookDao.listBooks();
}
@Transactional
public void updateBook(Ebook guide) {
bookDao.updateBook(guide);
}
@Transactional
public Ebook getBookById(Integer bookId) {
return bookDao.getBookById(bookId);
}
}
|
Ebook Controller
Now create a BookController which may have all the strategy we’d like for our CRUD operations. We have to wire the bookService for this controller utilizing @Autowired
annotation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
package deal org.techzoo.springmvc.controller;
import java.util.Map;
import org.springframework.beans.manufacturing facility.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.internet.bind.annotation.ModelAttribute;
import org.springframework.internet.bind.annotation.PathVariable;
import org.springframework.internet.bind.annotation.RequestMapping;
import org.springframework.internet.bind.annotation.RequestMethod;
import org.techzoo.springmvc.kind.Ebook;
import org.techzoo.springmvc.service.BookService;
@Controller
public class BookController {
@Autowired
personal BookService bookService;
@RequestMapping(“/index”)
public String listBooks(Map<String, Object> map) {
map.put(“guide”, new Ebook());
map.put(“bookList”, bookService.listBooks());
return “guide”;
}
@RequestMapping(
worth = “/guide/add”,
methodology = RequestMethod.POST
)
public String addBook(@ModelAttribute(“guide”)
Ebook guide, BindingResult end result)
{
if(null == guide.getId()) {
bookService.addBook(guide);
}
else {
bookService.updateBook(guide);
}
return “redirect:/index”;
}
@RequestMapping(“/delete/{bookId}”)
public String deleteBook(
@PathVariable(“bookId”) Integer bookId)
{
bookService.removeBook(bookId);
return “redirect:/index”;
}
@RequestMapping(“/edit/{bookId}”)
public String editBook(
@PathVariable(“bookId”)Integer bookId,
Map<String, Object> map)
{
map.put(“guide”, bookService.getBookById(bookId));
map.put(“bookList”, bookService.listBooks());
return “guide”;
}
}
|
SpringMVC Configuration
Now we’re all set with our java adjustments and we have to add spring relate configuration in xml recordsdata. First we add DispatcherServlet reference in internet.xml file. Following xml tags will add a DispatcherServlet reference to internet.xml file.
1
2
3
4
5
6
7
8
9
10
11
12
|
<servlet>
<servlet–identify>spring</servlet–identify>
<servlet–class>
org.springframework.internet.servlet.DispatcherServlet
</servlet–class>
<load–on–startup>1</load–on–startup>
</servlet>
<servlet–mapping>
<servlet–identify>spring</servlet–identify>
<url–sample>/</url–sample>
</servlet–mapping>
|
Now create a jdbc.properties
file which is used to set Database associated properties into it. We are able to add these properties immediately into spring xml file but it surely’s good to create a separate file and have all particulars of DB into it.
1
2
3
4
5
|
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/take a look at
jdbc.username=root
jdbc.password=
|
Hibernate Configuration
We’ve created a Hinerbate Entity Ebook which is annotation base Entity. The good thing about creating an annotation primarily based Entity class is We don’t must create a .hbm.xml file for that entity however we have to create hibernate.cfg.xml file for Hibernate associated configuration. Following XML reveals the mininum Hibernate configuration File.
1
2
3
4
5
6
7
8
9
10
11
|
xml model=‘1.0’ encoding=‘utf-8’?>
<!DOCTYPE hibernate–configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD//EN”
“http://hibernate.sourceforge.internet/hibernate-configuration-3.0.dtd”>
<hibernate–configuration>
<session–manufacturing facility>
<mapping class=“org.techzoo.springmvc.kind.Ebook” />
</session–manufacturing facility>
</hibernate–configuration>
|
Spring Configuration
Now we have to add spring-servler.xml file which include all beans and others MVC, Transaction associated Tags. XML file is minimal and self-explanatory.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
xml model=“1.0” encoding=“UTF-8”?>
<beans xmlns=“http://www.springframework.org/schema/beans”
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
xmlns:aop=“http://www.springframework.org/schema/aop”
xmlns:context=“http://www.springframework.org/schema/context”
xmlns:jee=“http://www.springframework.org/schema/jee”
xmlns:lang=“http://www.springframework.org/schema/lang”
xmlns:mvc=“http://www.springframework.org/schema/mvc”
xmlns:p=“http://www.springframework.org/schema/p”
xmlns:tx=“http://www.springframework.org/schema/tx”
xmlns:util=“http://www.springframework.org/schema/util”
xsi:schemaLocation=“http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd”>
<context:annotation–config />
<context:element–scan base–package deal=“org.techzoo.springmvc” />
<mvc:assets mapping=“/photographs/**” location=“/photographs/” />
<mvc:annotation–pushed />
<bean id=“jspViewResolver”
class=“org.springframework.internet.servlet.view.InternalResourceViewResolver”>
<property identify=“viewClass”
worth=“org.springframework.internet.servlet.view.JstlView” />
<property identify=“prefix” worth=“/WEB-INF/jsp/” />
<property identify=“suffix” worth=“.jsp” />
</bean>
<bean id=“messageSource”
class=“org.springframework.context.help.ReloadableResourceBundleMessageSource”>
<property identify=“basename” worth=“assets/messages” />
<property identify=“defaultEncoding” worth=“UTF-8” />
</bean>
<bean id=“propertyConfigurer”
class=“org.springframework.beans.manufacturing facility.config.PropertyPlaceholderConfigurer”
p:location=“/WEB-INF/jdbc.properties” />
<bean id=“dataSource”
class=“org.apache.commons.dbcp.BasicDataSource” destroy–methodology=“shut”
p:driverClassName=“${jdbc.driverClassName}”
p:url=“${jdbc.databaseurl}” p:username=“${jdbc.username}”
p:password=“${jdbc.password}” />
<bean id=“sessionFactory”
class=“org.springframework.orm.hibernate3.LocalSessionFactoryBean”>
<property identify=“dataSource” ref=“dataSource” />
<property identify=“configLocation”>
<worth>assets/hibernate.cfg.xml</worth>
</property>
<property identify=“configurationClass”>
<worth>org.hibernate.cfg.AnnotationConfiguration</worth>
</property>
<property identify=“hibernateProperties”>
<props>
<prop key=“hibernate.dialect”>${jdbc.dialect}</prop>
<prop key=“hibernate.show_sql”>true</prop>
<!—
<prop key=“hibernate.hbm2ddl.auto”>create</prop>
—>
</props>
</property>
</bean>
<tx:annotation–pushed />
<bean id=“transactionManager”
class=“org.springframework.orm.hibernate3.HibernateTransactionManager”>
<property identify=“sessionFactory” ref=“sessionFactory” />
</bean>
</beans>
|
View creation
Now final however not the least, creating view to indicate our Ebook Add Kind. I’ve additionally created a Desk grid which present the Listing of all obtainable Books after Ebook Entry kind. You’ll be able to click on on Ebook Identify and it’ll present the small print for the Ebook. Additional you’ll be able to edit the small print and Put it aside to Replace the Modifications.
guide.jsp