这篇文章简要介绍了如何使用spring3MVC注解和hibernate完成项目
用Eclipse作为开发工具,下图为项目结构
项目结构:
需要的jar包:
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> |
dispatcher-servlet.xml:
<context:property-placeholder> element specifies the location where to find the properties file. In our case it is jdbc.properties which should be available in class path. So we put this file within source folder in eclipse so that it can be put into the classes folder when deployed into the server.
<context:component-scan> element specifies from where to look for annotated components like @Repository, @Autowired etc.
<tx:annotation-driven> element specifies spring to look for @Transactional beans.
<bean id="dataSource"> provides properties to hibernate to make it able to create session factory.
Hibernate uses instance of session bean of typeorg.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean to make domain objects be able to get annotated at the code level rather than defining in xml files.
<property name="annotatedClasses"> element provides hibernate the list of annotated classes.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <context:property-placeholder location="classpath:jdbc.properties" /> <context:component-scan base-package="net.roseindia" /> <tx:annotation-driven transaction-manager="hibernateTransactionManager" /> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${database.driver}" /> <property name="url" value="${database.url}" /> <property name="username" value="${database.user}" /> <property name="password" value="${database.password}" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="annotatedClasses"> <list> <value>net.roseindia.model.Article</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> </props> </property> </bean> <bean id="hibernatetransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans> |
jdbc.properties
This file contains set of key and value pairs. The key is used in places to refer the value.
database.driver=com.mysql.jdbc.Driver database.url=jdbc:mysql://192.168.10.13/db_roseindia database.user=root database.password=root hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.show_sql=true |
Create Database and Table:
We are using the database and table given below in our application. Use the following sql script and create table.
create database if not exists `db_roseindia`; |
Article.java
Article is POJO class which hibernate uses to insert or retrieve data from database.
@Entity annotation is used to declare the POJO as persistent entity.
@Table annotation is used to map the POJO class to the table. In our case it is 'article' table in database.
@Id represents the identifier property.
@GeneratedValue declares that the identifier value will be generated by the database automatically.
@Column is used to map the property to the column of the table.
package net.roseindia.model; |
ArticleDao.java
This is an interface declaring the methods needed for the application.
package net.roseindia.dao; |
ArticleDaoImpl.java
This is the implementation class of ArticleDao interface.
@Repository("articleDao") declares that the annotated class is a "DAO".
@Autowired is being used to make the SessionFactory instance available automatically by spring.
Now, define the methods declared in ArticleDao interface using hibernate.
package net.roseindia.dao; |
ArticleService.java
This is the interface which declares methods which will be used in controller class.
package net.roseindia.service; |
ArticleServiceImpl.java
This is the implementation class of ArticleService Interface. It defines all the methods declared in ArticleService interface. These methods uses Dao classes to interact with the database.
@Service("articleService") annotation is used to declare it as service bean and its name articleService will be used to auto wire its instance in controller class.
@Transactional annotation is used to declare the method transactional. You can also use this at the class level to declare all methods transactional.
package net.roseindia.service; |
ArticleController.java
This is the spring controller class which handles the request, processes it and returns back to the client.
@Controller annotation declares this as a controller class.
@RequestMapping("/articles") annotation tells Spring to process all requests beginning with /articles.
@RequestMapping(method = RequestMethod.GET) annotation tells Spring to process the request url /articles.html.
package net.roseindia.controller; |
articlesList.jsp
This jsp file is called when /articles.html is requested.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <title>All Articles</title> </head> <body> <h1>List Articles</h1> <a href="articles/add.html">Add Article</a> <c:if test="${!empty articles}"> <table> <tr> <th>Article ID</th> <th>Article Name</th> <th>Article Desc</th> <th>Added Date</th> </tr> <c:forEach items="${articles}" var="article"> <tr> <td><c:out value="${article.articleId}"/></td> <td><c:out value="${article.articleName}"/></td> <td><c:out value="${article.articleDesc}"/></td> <td><c:out value="${article.addedDate}"/></td> </tr> </c:forEach> </table> </c:if> </body> </html> |
addArticle.jsp
This jsp file is called when articles/add.html is requested.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <html> <head><title>Add Article</title></head> <body> <h1>Add Article</h1> <c:url var="viewArticlesUrl" value="/articles.html" /> <a href="${viewArticlesUrl}">Show All Articles</a> <br /> <br /> <c:url var="saveArticleUrl" value="/articles/save.html" /> <form:form modelAttribute="article" method="POST" action="${saveArticleUrl}"> <form:label path="articleName">Article Name:</form:label> <form:input path="articleName" /> <br /> <form:label path="articleDesc">Article Desc:</form:label> <form:textarea path="articleDesc" /> <br /> <input type="submit" value="Save Article" /> </form:form> </body> </html> |
index.jsp
This is the index page which is called by default for application.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Spring 3 MVC and Hibernate 3 Example application using Annotations</title> </head> <body> <h1>Spring 3 MVC and Hibernate 3 Example application using Annotations</h1> <a href="articles.html">List of Articles</a> <a href="articles/add.html">Add Article</a> </body> </html> |
When we compile the application and run, it displays the output as below:
Click on List of Articles link. It displays all articles as below:
Click on Add Article link, it let you add article in database.