SSH系列(二):Spring + Hibernate + SpringMVC Maven整合
阿新 • • 發佈:2019-01-08
宣告:本文是關於Spring4.3.2 + Hibernate5.1.0 + SpringMVC Maven方式的簡單整合。pom.xml只添加了最基本的依賴,實際開發中需要的依賴根據專案具體新增; 本文不詳細說明maven安裝與使用。不當的地方歡迎大家指正,不勝感激。
整合環境
JDK 1.7
Tomcat:apache-tomcat-7.0.59
Spring:spring-framework-4.3.2.RELEASE
Hibernate:hibernate-release-5.1.0.Final
Maven工程目錄結構
整合步驟
MyEclipse中建立Maven工程
File –> New –> Project:
Next:
選擇建立原型:
指定原型引數:groupId、ArtifactID 和 version 等
注意:此時建立好工程中目錄如下圖,需要自己新增src/main/java、src/test/resource、src/test/java等目錄
pom.xml中新增依賴
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.test</groupId> <artifactId>spring_web_mvc_hibernate_maven_01</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>spring_web_mvc_hibernate_maven_02</name> <url>http://maven.apache.org</url> <properties> <springframework.version>4.3.2.RELEASE</springframework.version> <hibernate.version>5.1.0.Final</hibernate.version> <mysql.connector.version>5.1.13</mysql.connector.version> <javax.servlet-api.version>3.1.0</javax.servlet-api.version> <javax.servlet.jsp-api.version>2.3.1</javax.servlet.jsp-api.version> <jstl.version>1.2</jstl.version> <commons-dbcp.version>1.4</commons-dbcp.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- Spring --> <!-- 引入這個依賴會同時引入: spring-core-${springframework.version}.jar commons-logging-1.2.jar --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springframework.version}</version> </dependency> <!-- 引入這個依賴會同時引入: spring-web-${springframework.version}.jar spring-aop-${springframework.version}.jar spring-beans-${springframework.version}.jar spring-context-${springframework.version}.jar spring-expression-${springframework.version}.jar --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springframework.version}</version> </dependency> <!-- 引入這個依賴會同時引入: spring-webmvc-${springframework.version}.jar --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springframework.version}</version> </dependency> <!-- 引入這個依賴會同時引入: spring-tx-${springframework.version}.jar --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${springframework.version}</version> </dependency> <!-- 引入這個依賴會同時引入: spring-orm-${springframework.version}.jar spring-jdbc-${springframework.version}.jar --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${springframework.version}</version> </dependency> <!-- Hibernate --> <!-- 引入這個依賴會同時引入: hibernate-core-5.1.0.Final.jar jboss-logging-3.3.0.final.jar hibernate-jpa-2.1-apo-1.0.0.Final.jar javassist-3.20.0-GA.jar antlr-2.7.7.jar geronimo-jta_1.1_spec-1.1.1jar jandex-2.0.0.Final.jar classmate-1.3.0.jar dom4j-1.6.1.jar xml-apis-1.0.b2.jar hibernate-commons-annotations-5.0.1.Final.jar --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <!-- 資料庫連線池配置 --> <!-- 引入這個依賴會引入的包: commons-dbcp-1.4.jar commons-pool-1.5.4.jar --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>${commons-dbcp.version}</version> </dependency> <!-- 日誌 --> <!-- 引入這個依賴會引入的包: log4j-1.2.17.jar slf4j-api-1.7.21.jar slf4j-log4j12-1.7.7.jar --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.21</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.7</version> </dependency> <!-- MySQL --> <!-- 引入這個依賴會同時引入: mysql-connector-java-5.1.13.jar --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.connector.version}</version> </dependency> <!-- Servlet --> <!-- 引入這個依賴會同時引入: javax.servlet-api-3.1.0.jar --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${javax.servlet-api.version}</version> </dependency> <!-- jsp --> <!-- 引入這個依賴會同時引入: javax.servlet.jsp-api-2.3.1.jar --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>${javax.servlet.jsp-api.version}</version> </dependency> <!-- jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> </dependencies> <build> <finalName>spring_web_mvc_hibernate_maven_02</finalName> </build> </project>
程式碼示例
User:
package com.test.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name = "t_user") public class User implements Serializable { /** * */ private static final long serialVersionUID = 1405461442424049597L; private Integer uid; private String username; private String password; public User(Integer uid, String username, String password) { super(); this.uid = uid; this.username = username; this.password = password; } public User(String username, String password) { this(null, username, password); } @Id @GeneratedValue(generator = "increment") @GenericGenerator(name = "increment", strategy = "increment") public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } @Column(name = "uname") public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Column(name = "password") public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
Dao層:
IUserDao:
package com.test.dao;
import java.util.List;
import com.test.model.User;
public interface IUserDao {
public List<User> findAllUser();
}
UserDaoImpl:
package com.test.dao.impl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.test.dao.IUserDao;
import com.test.model.User;
@Repository
public class UserDaoImpl implements IUserDao {
@Autowired
private SessionFactory sessionFactory;
@Override
public List<User> findAllUser() {
String hql = "from User";
Session session = sessionFactory.openSession();
return session.createQuery(hql).list();
}
}
Service層:
IUserService:
package com.test.service;
import java.util.List;
import com.test.model.User;
public interface IUserService {
public List<User> findAllUser();
}
UserServiceImpl:
package com.test.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.test.dao.IUserDao;
import com.test.model.User;
import com.test.service.IUserService;
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private IUserDao userDao;
@Override
@Transactional(readOnly = true)
public List<User> findAllUser() {
return userDao.findAllUser();
}
}
Controller層:
package com.test.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.test.model.User;
import com.test.service.IUserService;
@Controller
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private IUserService userService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public ModelAndView getAllUser() {
List<User> list = userService.findAllUser();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("userList", list);
modelAndView.setViewName("/welcome");
return modelAndView;
}
}
配置檔案
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springmvc?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=warn, stdout
#log4j.logger.org.hibernate=info
log4j.logger.org.hibernate=debug
### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=info
### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=debug
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 掃描dao層的註解 -->
<context:component-scan base-package="com.test.dao.impl"/>
<!-- 載入資料庫配置檔案:db.properties -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 資料庫連線池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean>
<!-- 配置sessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
</props>
</property>
<!-- 配置需要掃描包的路徑,在該包下,所有的類註解配置都會被掃描 -->
<property name="packagesToScan" value="com.test.model"/>
</bean>
<!-- 掃描Service層的註解 -->
<context:component-scan base-package="com.test.service.impl"/>
<!-- 事務管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 開啟註解事務開關 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
springmvc.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 掃描帶有Controller的註解類 -->
<context:component-scan base-package="com.test.controller" />
<!-- 載入註解驅動 -->
<mvc:annotation-driven />
<!-- 檢視解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>