springmvc3+hibernate4入门配置
最近比较忙,电脑的桌面也比较乱了,在整理电脑桌面文件的时候,无意看到了以前学习时候的第一次写的springmvc例子,觉得挺适合新手入门的。在这里分享下配置吧,希望能帮到你。
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" 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_2_5.xsd"> <!--配置Log4j--> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/classes/config/log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <context-param> <param-name>webAppRootKey</param-name> <param-value>log4j_home</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!--设置字符编码 --> <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> <!--配置Spring--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/spring-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置SpringMVC --> <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*:config/spring-*.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!--控制Session的开关--> <filter> <filter-name>openSession</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>openSession</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--错误页面映射--> <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/common/error/ERROR_404.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/common/error/ERROR_403.jsp</location> </error-page> <error-page> <error-code>404</error-code> <location>/common/error/ERROR_404.jsp</location> </error-page> <error-page> <error-code>405</error-code> <location>/common/error/ERROR_405.jsp</location> </error-page> <error-page> <error-code>403</error-code> <location>/common/error/ERROR_403.jsp</location> </error-page> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <mapping class="com.xq.entity.User" /> </session-factory> </hibernate-configuration>
jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mvc jdbc.username=root jdbc.password=root jdbc.maxActive=255 jdbc.maxIdle=2 jdbc.maxWait=120000 jdbc.initialSize=10 jdbc.defaultAutoCommit=false hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.show_sql=true hibernate.hbm2ddl_auto=update hibernate.format_sql=false
log4j.properties
### FATAL, ERROR, WARN, INFO, DEBUG log4j.rootLogger=WARN,stdout,D ### 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 ### logFile ### ### save error to another file ### log4j.appender.D=org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File=${log4j_home}/WEB-INF/logs/log.log log4j.appender.D.Append=true ### error only in this file log4j.appender.D.Threshold=WARN log4j.appender.model.DatePattern='.'yyyy-MM-dd log4j.appender.D.layout=org.apache.log4j.PatternLayout log4j.appender.D.layout.COnversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss} [%t\:%r] - [%p] %m%n
spring-hibernate.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:cOntext="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd"> <!--读取属性文件,将属性文件保存到spring容器的map集合里--> <bean id="readConfig" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> <property name="location"> <value>classpath:config/jdbc.properties</value> </property> </bean> <!-- 配置数据库连接池 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="maxActive" value="${jdbc.maxActive}"/> <property name="maxIdle" value="${jdbc.maxIdle}"/> <property name="maxWait" value="${jdbc.maxWait}"/> <property name="initialSize" value="${jdbc.initialSize}"/> <property name="defaultAutoCommit" value="${jdbc.defaultAutoCommit}"/> </bean> <!--配置sessionFactory--> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="configLocation"> <value>classpath:config/hibernate.cfg.xml</value> </property> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl_auto}</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> <!--配置事务的传播特性--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="find*" propagation="REQUIRED" read-Only="true" /> <tx:method name="get*" propagation="REQUIRED" read-Only="true" /> <tx:method name="count*" propagation="REQUIRED" read-Only="true" /> <tx:method name="to*" propagation="REQUIRED" /> <tx:method name="*" read-Only="true" /> </tx:attributes> </tx:advice> <!--配置哪些类参与事务--> <aop:config expose-proxy="true"> <aop:pointcut id="txPointcut" expression="execution(* com.xq.service..*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" /> </aop:config> </beans>
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:cOntext="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util" 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-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <!--注解扫描的包--> <context:component-scan base-package="com.xq.*" /> <!--开启注解--> <mvc:annotation-driven /> <!--静态资源访问--> <mvc:default-servlet-handler/> <!--视图解释类--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑--> <property name="suffix" value=".jsp"></property> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> <!--上传文件--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8" /> <!--2*1024*1024=2M--> <property name="maxUploadSize" value="2097152" /> <!--40*1024=40K--> <property name="maxInMemorySize" value="40960" /> </bean> <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="java.lang.Exception">/common/error/ERROR_500</prop> <prop key="java.lang.Throwable">/common/error/ERROR_500</prop> </props> </property> <property name="statusCodes"> <props> <prop key="/common/error/ERROR_500">500</prop> <prop key="/common/error/ERROR_404">404</prop> </props> </property> <property name="warnLogCategory" value="WARN" /> <property name="defaultErrorView" value="/common/error/ERROR_500" /> <property name="defaultStatusCode" value="500" /> </bean> </beans>
HibernateSessionFactory.java
package com.xq.util; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * Hibernate4 获取sessionFactory和session工具类 * @author CXQ */ @Component public class HibernateSessionFactory{ /**注入Hibernate4的sessionFactory*/ @Autowired private SessionFactory sessionFactory; private Session session; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Session getSession() { session = sessionFactory.getCurrentSession(); return session; } public void setSession(Session session) { this.session = session; } }
IBaseDao.java
package com.xq.dao; import java.io.Serializable; import java.util.List; import java.util.Map; /** * 基础DAO接口 * @author CXQ */ public interface IBaseDao<T, ID extends Serializable>{ /** * 持久化新对象 * @param entity 实体 * @return 保存后的ID * @throws RuntimeException */ public ID save(T entity)throws RuntimeException; /** * 持久化新对象 或 更新已有对象 * @param entity 实体 * @throws RuntimeException */ public void saveOrUpdate(T entity)throws RuntimeException; /** * 更新已有对象 * @param entity 实体对象 * @throws RuntimeException */ public void update(T entity)throws RuntimeException; /** * 删除实体 * @param entity 实体 * @throws RuntimeException */ public void delete(T entity)throws RuntimeException; /** * 根据类和ID加载对象(延迟加载) * @param entityClass entity类 * @param id 唯一标识 * @return entity 实体对象 * @throws RuntimeException */ public T get(ID id)throws RuntimeException; /** * 根据类和ID加载对象(与之关联的对象一起加载) * @param entityClass entity类 * @param id 唯一标识 * @return entity 实体对象 * @throws RuntimeException */ public T find(ID id)throws RuntimeException; /** * 根据参数数值查询对象 * @param hql 语句 * @param param 参数对象数值 * @return entity 实体对象 * @throws RuntimeException */ public T findOnly(String hql, Object[] param) throws RuntimeException; /** * 根据单个属性属性值查询对象 - 仅用条件相等的 * @param propertyName 属性名 * @param propertyValue 属性值 * @return entity 实体对象 * @throws RuntimeException */ public T findOnlyEQ(String propertyName, Object propertyValue)throws RuntimeException; /** * 根据多个属性属性值查询对象 - 仅用条件相等的 * @param properties 属性集合Map<propertyName,propertyValue> * @return entity 实体对象 * @throws RuntimeException */ public T findOnlyEQ(Map<String, Object> properties)throws RuntimeException; /** * 根据单个属性属性值查询列表 - 仅用条件相等的 * @param propertyName 属性名 * @param propertyValue 属性值 * @return List * @throws RuntimeException */ public List<T> findEQ(String propertyName, Object propertyValue)throws RuntimeException; /** * 根据多个属性属性值查询列表 - 仅用条件相等的 * @param properties 属性集合Map<propertyName,propertyValue> * @return entity * @throws RuntimeException */ public List<T> findEQ(Map<String, Object> properties)throws RuntimeException; /** * 根据参数数值查询 * @param hql 语句 * @param param 参数对象数值 * @return List * @throws RuntimeException */ public List<T> find(String hql, Object[] param)throws RuntimeException; /** * 分页查询 * @param start 开始记录 * @param limit 显示记录数 * @return List * @throws RuntimeException */ public List<T> findPage(int start, int limit)throws RuntimeException; /** * 分页查询 * @param hql 语句 * @param param 参数对象数值 * @param start 开始记录 * @param limit 显示记录数 * @return List * @throws RuntimeException */ public List<T> findPage(String hql, Object[] param, int start, int limit)throws RuntimeException; /** * 查询所有实体 * @return List * @throws RuntimeException */ public List<T> findAll()throws RuntimeException; /** * 计算总记录数 * @return 总记录数 * @throws RuntimeException */ public long count()throws RuntimeException; /** * 根据条件计算总记录数 * @param hql 语句 * @param param 参数对象数值 * @return long * @throws RuntimeException */ public long count(String hql, Object[] param)throws RuntimeException; /** * 根据单个属性属性值统计 - 仅用条件相等的 * @param propertyName 属性名 * @param propertyValue 属性值 * @return List * @throws RuntimeException */ public long countEQ(String propertyName, Object propertyValue)throws RuntimeException; /** * 根据多个属性属性值统计 - 仅用条件相等的 * @param properties 属性集合Map<propertyName,propertyValue> * @return entity * @throws RuntimeException */ public long countEQ(Map<String, Object> properties)throws RuntimeException; /** * 使用Hibernate4 executeUpdate 修改或删除 * @param hql 修改或删除语句 * @param param 参数对象数值 * @return boolean * @throws RuntimeException */ public boolean exc(String hql, Object[] param)throws RuntimeException; }
BaseDaoImpl.java
package com.xq.dao.impl; import java.io.Serializable; import java.util.Iterator; import java.util.List; import java.util.Map; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import com.xq.dao.IBaseDao; import com.xq.util.HibernateSessionFactory; /** * 基础DAO实现类 * @author CXQ */ public class BaseDaoImpl<T, ID extends Serializable> extends HibernateSessionFactory implements IBaseDao<T, ID>{ /**实例类型*/ private Class<T> type; /** * BaseDaoImpl的构造方法 * @param type 实体类型 */ public BaseDaoImpl(Class<T> type) { this.type = type; } @SuppressWarnings("unchecked") public ID save(T entity) throws RuntimeException { return (ID)getSession().save(entity); } public void saveOrUpdate(T entity) throws RuntimeException { getSession().saveOrUpdate(entity); } public void update(T entity) throws RuntimeException { getSession().update(entity); } public void delete(T entity) throws RuntimeException { getSession().delete(entity); } @SuppressWarnings("unchecked") public T get(ID id) throws RuntimeException { return (T)getSession().load(type, id); } @SuppressWarnings("unchecked") public T find(ID id) throws RuntimeException { return (T)getSession().get(type, id); } @SuppressWarnings("unchecked") public T findOnly(String hql, Object[] param) throws RuntimeException { Query query = getSession().createQuery(hql); setQueryParams(query, param); return (T)query.uniqueResult(); } @SuppressWarnings("unchecked") public T findOnlyEQ(String propertyName, Object propertyValue) throws RuntimeException { Criteria criteria = getSession().createCriteria(type).add(Restrictions.eq(propertyName, propertyValue)); return (T)criteria.uniqueResult(); } @SuppressWarnings("unchecked") public T findOnlyEQ(Map<String, Object> properties) throws RuntimeException { Criteria criteria = getSession().createCriteria(type); setCriteriaMapParams(criteria, properties); return (T)criteria.uniqueResult(); } @SuppressWarnings("unchecked") public List<T> findEQ(String propertyName, Object propertyValue) throws RuntimeException { Criteria criteria = getSession().createCriteria(type).add(Restrictions.eq(propertyName, propertyValue)); return criteria.list(); } @SuppressWarnings("unchecked") public List<T> findEQ(Map<String, Object> properties) throws RuntimeException { Criteria criteria = getSession().createCriteria(type); setCriteriaMapParams(criteria, properties); return criteria.list(); } @SuppressWarnings("unchecked") public List<T> find(String hql, Object[] param) throws RuntimeException { Query query = getSession().createQuery(hql); setQueryParams(query, param); return query.list(); } @SuppressWarnings("unchecked") public List<T> findPage(int start, int limit) throws RuntimeException { Criteria criteria = getSession().createCriteria(type).setFirstResult(start).setMaxResults(limit); return criteria.list(); } @SuppressWarnings("unchecked") public List<T> findPage(String hql, Object[] param, int start, int limit) throws RuntimeException { Query query = getSession().createQuery(hql).setFirstResult(start).setMaxResults(limit); setQueryParams(query, param); return query.list(); } @SuppressWarnings("unchecked") public List<T> findAll() throws RuntimeException { Criteria criteria = getSession().createCriteria(type); return criteria.list(); } public long count() throws RuntimeException { Criteria criteria = getSession().createCriteria(type).setProjection(Projections.rowCount()); return ((Long)criteria.uniqueResult()).longValue(); } public long count(String hql, Object[] param) { Query query = getSession().createQuery(hql); setQueryParams(query, param); return ((Long)query.uniqueResult()).longValue(); } public long countEQ(String propertyName, Object propertyValue) throws RuntimeException { Criteria criteria = getSession().createCriteria(type).setProjection(Projections.rowCount()); criteria.add(Restrictions.eq(propertyName, propertyValue)); return ((Long)criteria.uniqueResult()).longValue(); } public long countEQ(Map<String, Object> properties) throws RuntimeException { Criteria criteria = getSession().createCriteria(type).setProjection(Projections.rowCount()); setCriteriaMapParams(criteria, properties); return ((Long)criteria.uniqueResult()).longValue(); } public boolean exc(String hql, Object[] param) throws RuntimeException { Query query = getSession().createQuery(hql); setQueryParams(query, param); return query.executeUpdate()==1?true:false; } /** * 设置查询条件的参数 * @param query * @param queryParams */ protected static void setQueryParams(Query query, Object[] queryParams){ if(queryParams==null||queryParams.length==0) return; for(int i=0; i<queryParams.length; i++){ query.setParameter(i, queryParams[i]); } } /** * 设置查询条件的参数 * @param criteria * @param properties */ protected static void setCriteriaMapParams(Criteria criteria, Map<String,Object> properties){ if(properties==null||properties.size()==0) return; Iterator<Map.Entry<String,Object>> it = properties.entrySet().iterator(); while(it.hasNext()){ Map.Entry<String,Object> entry = (Map.Entry<String,Object>)it.next(); String propertyName = (String)entry.getKey(); Object propertyValue = entry.getValue(); criteria.add(Restrictions.eq(propertyName, propertyValue)); } } }
好了太长了。不贴了,需要的自行下载demo。
这个不是maven项目,lib太大了15来m就不上传了,感叹还是maven好用,起码不用折腾这些依赖,目测jar好像太臃肿,有些是多余没用的包。或者如有需要我就@我。
spring-webmvc-portlet-3.2.6.RELEASE.jar
spring-webmvc-3.2.6.RELEASE.jar
spring-web-3.2.6.RELEASE.jar
spring-tx-3.2.6.RELEASE.jar
spring-test-3.2.6.RELEASE.jar
spring-oxm-3.2.6.RELEASE.jar
spring-orm-3.2.6.RELEASE.jar
spring-jms-3.2.6.RELEASE.jar
spring-jdbc-3.2.6.RELEASE.jar
spring-instrument-tomcat-3.2.6.RELEASE.jar
spring-instrument-3.2.6.RELEASE.jar
spring-expression-3.2.6.RELEASE.jar
spring-core-3.2.6.RELEASE.jar
spring-context-3.2.6.RELEASE.jar
spring-beans-3.2.6.RELEASE.jar
spring-aspects-3.2.6.RELEASE.jar
spring-aop-3.2.6.RELEASE.jar
mysql.jar
log4j-1.2.15.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar
jboss-logging-3.1.0.GA.jar
javassist-3.18.1-GA.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
hibernate-entitymanager-4.3.5.Final.jar
hibernate-core-4.2.15.Final.jar
hibernate-commons-annotations-4.0.2.Final.jar
dom4j-1.6.1.jar
commons-pool.jar
commons-logging-1.1.1.jar
commons-lang-2.5.jar
commons-io-2.0.1.jar
commons-fileupload-1.2.2.jar
commons-dbcp.jar
commons-collections-3.2.1.jar
aspectjweaver.jar
aopalliance.jar
antlr-2.7.7.jar
已下载:231 次
原创文章,转载请注明出处:https://www.weizhixi.com/article/60.html