Maven下Spring + SpringMvc + Hibernate4 配置实例

时间:2022-11-11 07:21:06

1. 开发环境 IDEA

2. 在pom.xml中配置引用相关的包。

<properties>
<junit.version>4.10</junit.version>
<log4j.version>2.0</log4j.version>
<mysql.jdbc.version>5.1.21</mysql.jdbc.version>
<hibernate.version>4.3.5.Final</hibernate.version>
<commons.fileupload.version>1.2.1</commons.fileupload.version>
<javassist.version>3.12.1.GA</javassist.version>
<cxf.version>3.0.2</cxf.version>
<spring.version>4.1.3.RELEASE</spring.version>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency> <!-- cxf -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-core</artifactId>
<version>${cxf.version}</version>
</dependency> <!-- 读取字节码包 -->
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>${javassist.version}</version>
</dependency> <dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency> <!-- commons配置 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons.fileupload.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency> <!-- log4j的依赖 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency> <!-- mysql的依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.jdbc.version}</version>
</dependency> <!-- hibernate部分 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency> <!-- c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency> <!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-hibernate3</artifactId>
<version>2.0.8</version>
</dependency> <!-- aspectj -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjlib</artifactId>
<version>1.6.2</version>
</dependency> <!-- quartz -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.0</version>
</dependency> <dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>1.3</version>
</dependency> </dependencies> <build>
<finalName>hibernatedemo</finalName>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>tomcat-maven-plugin</artifactId>
<version>1.1</version>
<configuration>
<path>/hibernatedemo</path>
<port>8080</port>
<uriEncoding>UTF-8</uriEncoding>
<url>http://localhost:8080/hibernatedemo/index</url>
<server>tomcat6</server>
</configuration>
</plugin>
</plugins>
</build>

3. 创建Java 代码结构如下:

Maven下Spring + SpringMvc + Hibernate4 配置实例

TestController:

 @Autowired
private UsersDAO usersDAO; @RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView indexGet(){
List<Users> list = usersDAO.getAllUser();
ModelAndView mv = new ModelAndView("index") ;
mv.addObject("size", list.size());
return mv;
} @RequestMapping(value = "/", method = RequestMethod.GET)
@ResponseBody
public String defaultGet(){
return "default" ;
}

UsersDAO

public class UsersDAO {
private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
} public List<Users> getAllUser(){
String hsql="from Users";
Session session = sessionFactory.openSession();
Query query = session.createQuery(hsql); return query.list();
}
}

Users

@Entity()
//@Table(name="users")
public class Users { public Users(){ } @Id
@GeneratedValue
public Long id ; public String name;
public String email;
public String password; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
}
}

4. 配置Spring 和 Hibernate4 Xml 设置,文件放在代码目录中的resources文件夹中

spring-hibernate.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:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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
"> <!-- Hibernate4 -->
<!-- 加载资源文件 其中包含变量信息,必须在Spring配置文件的最前面加载,即第一个加载-->
<context:property-placeholder location="classpath:persistence-mysql.properties" /> <bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<!-- 可以加多个包 -->
<value>priv.bruce.demoproject.hibernatedemo.model</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<!-- <prop key="hibernate.current_session_context_class">thread</prop> --> </props> </property>
</bean> <!-- 数据库映射 -->
<!-- class="org.apache.tomcat.dbcp.dbcp.BasicDataSource" -->
<!-- class="org.springframework.jdbc.datasource.DriverManagerDataSource" -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.user}" />
<property name="password" value="${jdbc.pass}" />
</bean> <!-- 配置Hibernate事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> <!-- 配置事务异常封装 -->
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /> <!-- 声明式容器事务管理 ,transaction-manager指定事务管理器为transactionManager -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="get*" propagation="REQUIRED" />
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice> <!--<aop:config expose-proxy="true">-->
<!--&lt;!&ndash; 只对业务逻辑层实施事务 &ndash;&gt;-->
<!--<aop:pointcut id="txPointcut" expression="execution(* com.lei.demo.service..*.*(..))" />-->
<!--&lt;!&ndash; Advisor定义,切入点和通知分别为txPointcut、txAdvice &ndash;&gt;-->
<!--<aop:advisor pointcut-ref="txPointcut" advice-ref="txAdvice"/>-->
<!--</aop:config>--> <bean id="usersDAO" class="priv.bruce.demoproject.hibernatedemo.dao.UsersDAO">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean> </beans>

系统参数配置文件 persistence-mysql.properties

# jdbc.X
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://datasource?useUnicode=true&characterEncoding=utf8
jdbc.user=root
jdbc.pass=123456 # hibernate.X
hibernate.connection.driverClass=org.gjt.mm.mysql.Driver
hibernate.connection.url=jdbc:mysql://datasource?useUnicode=true&characterEncoding=utf8
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.connection.username=root
hibernate.connection.password=pass
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop

5. Spring Mvc 配置

  5.1  webapp中增加view 用做保存 velocity模版

  5.2 配置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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 定义DispatcherServlet -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- 默认/WEB-INF/[servlet名字]-servlet.xml加载上下文,
如果配置了contextConfigLocation参数,
将使用classpath:/lei-dispatcher-servlet.xml加载上下文
-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 拦截匹配的请求,这里所有请求采用名字为lei-dispatcher的DispatcherServlet处理 --> <servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

  5.3 配置 dispatcher-servlet.xml, 文件放在resources文件夹中,也可以自行配置文件所在位置。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
"> <!-- 启动自动扫描该包下所有的Bean(例如@Controller) -->
<context:component-scan base-package="priv.bruce.demoproject.hibernatedemo.controller" /> <!-- velocity解析器,替换掉原来的jsp -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="contentType" value="text/html;charset=UTF-8" />
<property name="suffix" value=".html" />
</bean> <bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath">
<value>WEB-INF/views/</value>
</property>
<property name="velocityProperties">
<props>
<prop key="input.encoding">UTF-8</prop>
<prop key="output.encoding">UTF-8</prop>
<prop key="contentType">text/html;charset=UTF-8</prop>
</props>
</property>
</bean>
</beans>

  5.4 创建 模板 index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
size: $!size
</body>
</html>

6. 创建数据表,插入一条记录。

CREATE TABLE `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`email` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

7. 启动项目输入地址: http://127.0.0.1:8080/hibernatedemo/index

 显示:size: 1

 表示项目已经运行成功

源码下载地址:

https://github.com/zj1111184556/demoproject