![](https://img.haomeiwen.com/i7119847/02e2c3279defe7b6.jpg)
Spring+SpringMVC的maven工程整合hibernate
一: maven依赖
- 各个依赖版本信息
<spring.version>4.3.1.RELEASE</spring.version>
<hibernate.version>4.3.5.Final</hibernate.version>
<mysql.version>5.1.38</mysql.version>
<c3p0.version>0.9.1.2</c3p0.version>
- spring
<!-- spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
- springmvc
<!-- spring web + spring MVC-->
<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>
- hibernate
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
- mysql
<dependency>
<groupId>mysql</groupId>
<version>${mysql.version}</version>
<artifactId>mysql-connector-java</artifactId>
</dependency>
- c3p0数据库连接池
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
SpringMVC的配置 orcish-servlet
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<!-- 使用基于注解的控制器,spring会自动扫描base-package下的子包和类,如果扫描到会把这些类注册为bean-->
<!--<context:component-scan base-package="cn.orcish"/>-->
<context:component-scan base-package="cn.orcish">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--<context:annotation-config/>-->
<!--json支持-->
<mvc:annotation-driven />
<!-- 配置处理映射器和处理器适配器 在Spring4.0后,不配置,会默认加载-->
<!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>-->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> -->
<!-- 会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter两个Bean -->
<!--<mvc:annotation-driven/>-->
<!-- 配置视图解析器,经过视图解析器后,视图的的完成路径为[prefix]+返回的视图字符串+[suffix] -->
<bean id="templateResolver"
class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="WEB-INF/view/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
<property name="cacheable" value="false" />
<property name="characterEncoding" value="UTF-8"/>
</bean>
<bean id="templateEngine"
class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<!--多视图配置Thymeleaf和jsp-->
<property name="viewResolvers">
<list>
<!--used thymeleaf -->
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="characterEncoding" value="UTF-8"/>
<property name="templateEngine" ref="templateEngine" />
<property name="viewNames" value="*"/>
<!--权重-->
<property name="order" value="0" />
</bean>
<!-- used jsp -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
<property name="viewNames" value="*"/>
<property name="order" value="1" />
</bean>
</list>
</property>
</bean>
<!--这里是对静态资源的映射-->
<mvc:resources mapping="/js/**" location="/resources/js/" />
<mvc:resources mapping="/css/**" location="/resources/css/" />
<mvc:resources mapping="/image/**" location="/resources/image/" />
<mvc:resources mapping="/fonts/**" location="/resources/fonts/" />
</beans>
数据库连接信息和Hibernate的配置config.properties
#database connection config
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://127.0.0.1:3306/shiro_demo?useUnicode=true&characterEncoding=utf-8
jdbc.username = orcish
jdbc.password = 123456
#hibernate config
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto = update
Spring的配置
<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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- 自动扫描 -->
<context:component-scan base-package="cn.orcish">
<!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--********************************************配置hibernate********************************************-->
<!--扫描配置文件(这里指向的是之前配置的那个config.properties)-->
<context:property-placeholder location="classpath:/config.properties" />
<!--配置数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${jdbc.driver}" /> <!--数据库连接驱动-->
<property name="jdbcUrl" value="${jdbc.url}" /> <!--数据库地址-->
<property name="user" value="${jdbc.username}" /> <!--用户名-->
<property name="password" value="${jdbc.password}" /> <!--密码-->
<property name="maxPoolSize" value="40" /> <!--最大连接数-->
<property name="minPoolSize" value="1" /> <!--最小连接数-->
<property name="initialPoolSize" value="10" /> <!--初始化连接池内的数据库连接-->
<property name="maxIdleTime" value="20" /> <!--最大空闲时间-->
</bean>
<!--配置session工厂-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="cn.orcish.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!--hibernate根据实体自动生成数据库表-->
<prop key="hibernate.dialect">${hibernate.dialect}</prop> <!--指定数据库方言-->
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <!--在控制台显示执行的数据库操作语句-->
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <!--在控制台显示执行的数据哭操作语句(格式)-->
</props>
</property>
</bean>
<!-- 事物管理器配置 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!--加载Spring的配置文件到上下文中去-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
springmvc start
源码:spring-web.jar
默认配置:/WEB-INF/${servlet-name}-servlet.xml,即/WEB-INF/orcish-servlet.xml
覆盖默认配置:初始化参数:contextConfigLocation,参数多个值使用逗号隔开,如:a.xml,b.xml
-->
<servlet>
<servlet-name>orcish</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:orcish-servlet.xml</param-value>
</init-param>
<!-- 容器初始化加载此servlet -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>orcish</servlet-name>
<!--
一般有以下写法:
*.do 拦截固定格式的请求
/ rest风格的写法:拦截所有资源,需要针对静态资源做单独处理
/* 错误写法:会在处理完请求后拦截jsp导致404错误
-->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--
character filter start
源码:spring-web.jar
功能:字符集过滤器,设置编码集为UTF-8,解决POST的中文乱码问题。
参数说明:
encoding:request的编码集(request.setCharacterEncoding("UTF-8"))
forceEncoding:默认为false设置为true,response的编码集也强制转变成UTF-8(response.setCharacterEncoding("UTF-8"))
-->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
测试
- maven依赖
<!--junit-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
-
dao和daoTest
@Repository public class UserDaoImpl implements UserDao { @Autowired private SessionFactory sessionFactory; private Session getCurrentSession(){ return sessionFactory.openSession(); } public List<User> findAll() { //查询列表三种方式之一 String hql = "from User"; Query query = getCurrentSession().createQuery(hql); List<User> list = query.list(); //查询列表三种方式之二 Criteria criteria = getCurrentSession().createCriteria(User.class); list = criteria.list(); //查询列表三种方式之三 SQLQuery sqlQuery = getCurrentSession().createSQLQuery("select * from tp_user"); sqlQuery.addEntity(User.class); list = sqlQuery.list(); return query.list(); } } @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:applicationContext.xml"}) public class UserDaoImplTest extends TestCase { @Autowired private UserDao userDao; @Test public void testFindAll() throws Exception { List<User> list = userDao.findAll(); System.out.println(list); } }
网友评论