之前一直使用spring3+status+hibernate3做开发,但是使用的技术,好像有点老了,于是,今天研究了下Spring4+SpringMVC4+hibernate4+druid+fastjson,现将搭建项目源码分享出来,希望对你有帮助。
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.sofn</groupId> <artifactId>sofn.cms</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>sofn.cms Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- spring版本号 --> <spring.version>4.3.0.RELEASE</spring.version> </properties> <!-- 指定maven仓库 --> <repositories><!-- 发现依赖和扩展的远程资源库 --> <!-- maven自己官方仓库 --> <repository> <id>maven</id> <name>Maven Repository Switchboard</name> <layout>default</layout> <url>http://repo1.maven.org/maven2</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> <!-- 阿里巴巴发布版本仓库 --> <repository> <id>alibaba-opensource</id> <name>alibaba-opensource</name> <url>http://code.alibabatech.com/mvn/releases/</url> <layout>default</layout> </repository> <!-- 阿里巴巴快照版本仓库 --> <repository> <id>alibaba-opensource-snapshot</id> <name>alibaba-opensource-snapshot</name> <url>http://code.alibabatech.com/mvn/snapshots/</url> <layout>default</layout> </repository> </repositories> <dependencies><!-- 这个元素描述了所有与当前项目相关的依赖 --> <!-- junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> <scope>provided</scope> </dependency> <!-- log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2.1-b03</version> <scope>provided</scope> </dependency> <!-- 文件上传 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <!-- fastJson json数组有关的 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.23</version> </dependency> <!-- mysql数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> <!-- druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.18</version> </dependency> <!-- aspectjweaver.jar这是Spring AOP所要用到的包 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.1</version> </dependency> <!-- hibernate4 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.2.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.2.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>4.2.5.Final</version> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId> <version>1.0.1.Final</version> </dependency> <!-- spring mvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- spring4 --> <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-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</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-expression</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-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>RELEASE</version> </dependency> </dependencies> <build> <finalName>sofn.cms</finalName> </build> </project>
config.properties
#\u5C5E\u6027\u6587\u4EF6 #Oracle \u7684\u914D\u7F6E hibernate.dialect=org.hibernate.dialect.OracleDialect driverClassName=oracle.jdbc.driver.OracleDriver validationQuery=SELECT 1 FROM DUAL jdbc_url=jdbc:oracle:thin:@192.168.21.139:1521:moonl jdbc_username=sofn_sx jdbc_password=sofn_sx #SQLServer \u7684\u914D\u7F6E #hibernate.dialect=org.hibernate.dialect.SQLServerDialect #driverClassName=net.sourceforge.jtds.jdbc.Driver #validationQuery=SELECT 1 #jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/sy #jdbc_username= #jdbc_password= #Derby \u7684\u914D\u7F6E #hibernate.dialect=org.hibernate.dialect.DerbyDialect #driverClassName=org.apache.derby.jdbc.EmbeddedDriver #validationQuery=SELECT 1 #jdbc_url=jdbc:derby:sy;create=true #jdbc_username= #jdbc_password= #MySQL \u7684\u914D\u7F6E #hibernate.dialect=org.hibernate.dialect.MySQLDialect #driverClassName=com.mysql.jdbc.Driver #validationQuery=SELECT 1 #jdbc_url=jdbc:mysql://localhost:3306/sshf?useUnicode=true&characterEncoding=utf-8 #jdbc_username=root #jdbc_password= hibernate.hbm2ddl.auto=update hibernate.show_sql=true hibernate.format_sql=false sessionInfoName=sessionInfo uploadFieldName=filedata uploadFileMaxSize=20971520 uploadFileExts=txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid uploadDirectory=attached
log4j.properties
log4j.rootLogger=INFO,A1,R log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.Target=System.out log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=[%c]%m%n log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.File=sshf.log log4j.appender.R.MaxFileSize=10MB log4j.appender.R.Threshold=ALL log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n
applicationContext.xml
<?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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" 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.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <context:component-scan base-package="org.moon.framework.dao,org.moon.framework.service" /> <!-- 引入属性文件 --> <context:property-placeholder location="classpath:config.properties" /> <!-- 配置数据源 --> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc_url}" /> <property name="username" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="0" /> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="20" /> <!-- 连接池最大空闲 --> <property name="maxIdle" value="20" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="0" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="60000" /> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> <property name="validationQuery" value="${validationQuery}" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true" /> <!-- 监控数据库 --> <property name="filters" value="stat" /> <!--<property name="filters" value="mergeStat" />--> </bean> <!-- 配置hibernate session工厂 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <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.format_sql">${hibernate.format_sql}</prop> </props> </property> <!-- 自动扫描注解方式配置的hibernate类文件 --> <property name="mappingDirectoryLocations"> <list> <value>classpath:hbm</value> </list> </property> </bean> <!-- 配置事务管理器 --> <bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> <!--使用hibernateTemplate 模板--> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!--通用的dao查询方法--> <bean id="baseDAO" class="org.moon.framework.dao.impl.BaseDAOImpl"> <property name="hibernateTemplate" ref="hibernateTemplate"></property> <property name="dataSource" ref="dataSource"></property> </bean> </beans>
spring-mvc.xml
<?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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" 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.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <context:component-scan base-package="org.moon.framework.controller "/> <!-- 开启mvc注解 --> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <!-- 配置Fastjson支持 --> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json</value> </list> </property> <property name="features"> <list> <value>WriteMapNullValue</value> <value>QuoteFieldNames</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 定义跳转的文件的前后缀 ,视图模式配置--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>Archetype Created Web Application</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 编码过滤器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止Spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <filter> <filter-name>DruidWebStatFilter</filter-name> <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class> <init-param> <param-name>exclusions</param-name> <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value> </init-param> <init-param> <param-name>sessionStatMaxCount</param-name> <param-value>2000</param-value> </init-param> <init-param> <param-name>sessionStatEnable</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>principalSessionName</param-name> <param-value>session_user_key</param-value> </init-param> <init-param> <param-name>profileEnable</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>DruidWebStatFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>DruidStatView</servlet-name> <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class> <init-param> <!-- 允许清空统计数据 --> <param-name>resetEnable</param-name> <param-value>true</param-value> </init-param> <init-param> <!-- 用户名 --> <param-name>loginUsername</param-name> <param-value>druid</param-value> </init-param> <init-param> <!-- 密码 --> <param-name>loginPassword</param-name> <param-value>druid</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>DruidStatView</servlet-name> <url-pattern>/druid/*</url-pattern> </servlet-mapping> <!-- Spring MVC servlet --> <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:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 --> <url-pattern>/</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.gif</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.jpg</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.woff</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.woff2</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.ttf</url-pattern> </servlet-mapping> <session-config> <session-timeout>10</session-timeout> </session-config> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app>
到此,配置文件,已经编辑完成
现在我们来做下测试
TestSpring.java
package org.moon; import org.apache.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.moon.framework.beans.Menus; import org.moon.framework.dao.BaseDAO; import org.moon.framework.service.BaseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.sql.DataSource; import java.util.List; /** * Created by Administrator on 2016/12/30. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationContext.xml"}) public class TestSpring { private static Logger logger = Logger.getLogger(TestSpring.class); @Autowired private ApplicationContext applicationContext; @Autowired private BaseService baseService; @Test public void test(){ String hql = "from Menus vo"; List<Menus> list = (List<Menus>)baseService.pageQuery(hql,0,10); for (Menus menus : list) { System.out.println(menus.getName()); } } }
看到这里,对spring,hibernate,SpringMVC比较熟悉的同学,应该可以跑起来了,如果没有跑起来,那就把剩下的代码也贴出来。
bean目录下
AbstractValueObject.java
package org.moon.framework.beans.pub; import java.io.Serializable; import java.util.Date; public abstract class AbstractValueObject implements Comparable, Serializable { Date ts; public AbstractValueObject() { } public AbstractValueObject(String pk) { setPrimaryKey(pk); } public String getEntityName() { return ""; } abstract public String getPrimaryKey(); abstract public void setPrimaryKey(String key); public String toString() { return getPrimaryKey(); } public Date getTs() { return ts; } public void setTs(Date ts) { this.ts = ts; } /** * 克隆一个完全相同的VO对象(前层复制)。 * * 创建日期:(2007-3-7 11:34:51) * * @return Object */ public Object clone() { Object o = null; try { o = super.clone(); } catch (CloneNotSupportedException e) { System.out.println("clone not supported!"); } return o; } public int compareTo(Object o) { return 0; } }
Menus.java
package org.moon.framework.beans; import org.moon.framework.beans.pub.AbstractValueObject; import java.util.List; /** * Created by Administrator on 2016/12/30. */ public class Menus extends AbstractValueObject { public String pk_menus;// 主键 public String name; // 名称 public String enname; // 英文名称 public String action; // 请求 public String target; // 目标 public String rel; // 关联 public Integer orders; // 排序 public Boolean islock; // 是否锁定 public String parent_pk; // 上级菜单 public List<Menus> listMenus;// 菜单子集 // public String getPrimaryKey() { return pk_menus; } public void setPrimaryKey(String key) { this.pk_menus = key; } public String getPk_menus() { return pk_menus; } // pk_menus set public void setPk_menus(String pk_menus) { this.pk_menus = pk_menus; } // 名称 get public String getName() { return name; } // 名称 set public void setName(String name) { this.name = name; } // 英文名称 get public String getEnname() { return enname; } // 英文名称 set public void setEnname(String enname) { this.enname = enname; } // 请求 get public String getAction() { return action; } // 请求 set public void setAction(String action) { this.action = action; } // 目标 get public String getTarget() { return target; } // 目标 set public void setTarget(String target) { this.target = target; } // 关联 get public String getRel() { return rel; } // 关联 set public void setRel(String rel) { this.rel = rel; } // 排序 get public Integer getOrders() { return orders; } // 排序 set public void setOrders(Integer orders) { this.orders = orders; } // 是否锁定 get public Boolean getIslock() { return islock; } // 是否锁定 set public void setIslock(Boolean islock) { this.islock = islock; } // 上级菜单 get public String getParent_pk() { return parent_pk; } // 上级菜单 set public void setParent_pk(String parent_pk) { this.parent_pk = parent_pk; } public List<Menus> getListMenus() { return listMenus; } public void setListMenus(List<Menus> listMenus) { this.listMenus = listMenus; } }
dao目录下
BaseDAO.java
package org.moon.framework.dao; import java.util.List; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.orm.hibernate4.HibernateTemplate; import javax.sql.DataSource; public interface BaseDAO { /** * 分页查询 * * @param hql * @param first * @param max * @return */ public List<?> pageQuery(String hql, final int first, final int max); /** * 查询数据行数 * * @param hql * @return */ public int queryCount(String hql); /** * 查询所有数据 * * @param hql * @return */ public List<?> query(String hql); public List<?> query(String hql, Object[] args); /** * 获取当前日期 * * @return */ public String getDate(); /** * 获取当前时间 * * @return */ public String getDateTime(); public JdbcTemplate getJdbcTemplate(); }
BaseDAOImpl.java
package org.moon.framework.dao.impl; import javax.annotation.Resource; import javax.sql.DataSource; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.moon.framework.dao.BaseDAO; import org.moon.framework.util.date.DateUtilServer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.orm.hibernate4.HibernateCallback; import org.springframework.orm.hibernate4.HibernateTemplate; import org.springframework.orm.hibernate4.support.HibernateDaoSupport; import org.springframework.stereotype.Repository; import java.util.Date; import java.util.List; /** * Created by Administrator on 2016/12/30. */ @Repository("baseDAO") public class BaseDAOImpl extends HibernateDaoSupport implements BaseDAO { // 数据源 @Autowired public DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } @Autowired public void setSessionFactoryOverride(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); } public List<?> pageQuery(final String hql, final int first, final int max) { List<?> list = (List<?>) getHibernateTemplate().execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Query queryObject = session.createQuery(hql); queryObject.setFirstResult(first); queryObject.setMaxResults(max); return queryObject.list(); } }); return list; } /** * 查询某个对象的个数 * * @param hql * @return */ public int queryCount(String hql) { String sql = hql; if (sql.toLowerCase().startsWith("select ")) { sql = "select count(*) " + hql.substring(hql.toLowerCase().indexOf("from")); } else { sql = "select count(*) " + hql; } List<?> list = getHibernateTemplate().find(sql); if (list.size() == 0) { return 0; } return ((Long) list.get(0)).intValue(); } /** * 查询全部数据 */ public List<?> query(String hql) { return getHibernateTemplate().find(hql); } /** * 根据条件查询全部数据 */ public List<?> query(String hql, Object[] args) { return getHibernateTemplate().find(hql, args); } public String getDate() { String date = DateUtilServer.dateToString(new Date(), "yyyy-MM-dd"); return date; } public String getDateTime() { String datetime = DateUtilServer.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"); return datetime; } public JdbcTemplate getJdbcTemplate() { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); return jdbcTemplate; } }
service部分
BaseService.java
package org.moon.framework.service; import org.moon.framework.beans.Menus; import org.moon.framework.dao.BaseDAO; /** * Created by Administrator on 2016/12/30. */ public interface BaseService extends BaseDAO { public void save(Object vo); public void delete(Object vo); public Object getObject(Class clzz,String pk); }
BaseServiceImpl.java
package org.moon.framework.service.impl; import org.moon.framework.dao.impl.BaseDAOImpl; import org.moon.framework.service.BaseService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * Created by Administrator on 2016/12/30. */ @Service("baseService") public class BaseServiceImpl extends BaseDAOImpl implements BaseService { /** * 添加数据或者修改数据 注:ts为Date类型,为乐观锁标记 * @param vo */ @Transactional(propagation= Propagation.REQUIRED) public void save(Object vo) { getHibernateTemplate().saveOrUpdate(vo); } /** * 数据删除 * @param vo */ @Transactional(propagation= Propagation.REQUIRED) public void delete(Object vo) { getHibernateTemplate().delete(vo); } /** * 获取单条数据 * @param clzz * @param pk * @return */ public Object getObject(Class clzz,String pk) { return getHibernateTemplate().get(clzz,pk); } }
Controller部份
package org.moon.framework.controller; import org.moon.framework.beans.PageInfo; import org.moon.framework.service.BaseService; 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.ResponseBody; import java.util.List; /** * Created by Administrator on 2016/12/30. */ @Controller @RequestMapping(value = "/base") public class BaseController { @Autowired private BaseService baseService; /** * 默认的获取操作的bean对象名称 * @return */ public String getBeanName(){ return ""; } /** * 默认查询条件 * @return */ public String getWhere(){ return ""; } /** * 默认的排序 * @return */ public String getOrders(){ return ""; } /** * * @param start * @param length * @return */ @RequestMapping("/pageInfo") @ResponseBody public PageInfo pageList(int start,int length,Object vo){ PageInfo pageInfo = new PageInfo(); String hql = "from "+getBeanName()+" vo"; List<?> list = baseService.pageQuery(hql,start,length); int count = baseService.queryCount(hql); pageInfo.setPageNum(start); pageInfo.setPageSize(length); pageInfo.setList(list); pageInfo.setTotal(count); return pageInfo; } }
BaseController.java 是用于具体实现的*Controller继承
并且重写:getBeanName()方法,将Bean对象的名称放入
如果还不清楚,那就请留言吧!
相关推荐
在本项目"spring4+springmvc4+hibernate4 整合"中,我们将探讨这三者的集成过程,以及它们如何协同工作来构建高效、可维护的Web应用程序。 **Spring Framework 4** Spring 是一个全面的Java应用框架,提供依赖注入...
5. **源码分析**:对于"Spring4+SpringMVC4+Hibernate4整合源码",研究这些源码可以帮助开发者深入理解三大框架的内部工作原理,学习如何配置和使用它们进行实际项目开发。通过源码,你可以看到如何配置Spring的...
Java基于Spring+SpringMVC+MyBatis实现的学生信息管理系统源码,SSM+Vue的学生管理系统。 Java基于Spring+SpringMVC+MyBatis实现的学生信息管理系统源码,SSM+Vue的学生管理系统。 Java基于Spring+SpringMVC+...
【Java框架】spring4+springmvc4+mybatis3.3.0+druid多数据源案例.zip spring4+springmvc4+mybatis3.3.0+druid多数据源demo,同时支持mybatis generator代码生成器(java代码、maven插件式的生成都有相应代码和配置...
完善的Spring+SpringMVC+Mybatis+easyUI后台管理系统(RESTful API+redis).zip 完善的Spring+SpringMVC+Mybatis+easyUI后台管理系统(RESTful API+redis).zip 完善的Spring+SpringMVC+Mybatis+easyUI后台管理系统...
标题中的"idea工具创建的Spring+SpringMVC+Hibernate+maven项目"指的是使用IntelliJ IDEA这个集成开发环境(IDE)构建的一个Java Web项目,该项目整合了四个关键的技术框架:Spring、SpringMVC、Hibernate以及Maven...
在现代Java Web开发中,"Maven整合Spring+SpringMVC+Hibernate+SpringDataJPA"是一个常见的架构组合,被广泛应用于构建企业级应用程序。这个组合通常被称为"SSM",其中"M"代表Maven,"S"代表Spring,包括Spring核心...
这个项目“Spring4+hibernate4+SpringMVC+Maven”就是一个典型的Java Web开发组合,它利用了四个关键组件:Spring 4、Hibernate 4、Spring MVC和Maven。让我们逐一探讨这些技术及其在项目中的作用。 1. **Spring 4*...
基于Spring+SpringMVC+Mybatis架构的博客系统:博客管理、图表数据、日志分析、访问记录、图库管理、资源管理、友链通知等。良好的页面预加载,无限滚动加载,文章置顶,博主推荐等。提供 用户端+管理端 的整套系统...
Spring+SpringMVC+Hibernate 框架集成详解 本文档旨在详细介绍 Spring、SpringMVC 和 Hibernate 框架的集成,旨在帮助开发人员快速了解这三个框架的集成过程。 Spring 框架 Spring 框架是一个 Java 语言的开源...
《Spring4+Mybatis3+SpringMVC4实战》是一个基于这三个流行开源框架构建的完整项目,旨在帮助学习者深入理解和实践SSM(Spring、SpringMVC、Mybatis)架构。这个项目涵盖了从基础配置到高级特性的全方位应用,对于...
Spring4 SpringMVC MyBatis 模板引擎beetl 前端bootstrap 数据源druid 缓存ehcache MyBatis分页插件PageHelper MyBatis通用Mapper 源码完整+带sql脚本+亲测可以用,而且功能很强大,是一个完善的框架实例。
在"Spring3+SpringMVC+MyBatis"的整合过程中,通常会使用Spring的ApplicationContext来加载配置,管理所有组件。SpringMVC的配置需要定义DispatcherServlet,配置视图解析器如InternalResourceViewResolver,以及...
整合搭建Spring+SpringMVC+Mybatis+Maven+Mysql开发实例
"spring3+springmvc+jpa+hibernate多数据源"是一个示例项目,它演示了如何在一个应用中集成Spring 3、Spring MVC、JPA 2.0以及Hibernate,以实现对多个数据源的支持。下面将详细介绍这些技术及其集成的关键点。 **...
类似于淘宝的购物网站,前端使用JQuery EasyUI,后端使用Spring4+SpringMVC4+Mybatis3,数据库使用MySQL5.7,开发平台IntelliJ IDEA(2018.3)+open JDK1.8 amd64+MacOS.zip类似于淘宝的购物网站,前端使用JQuery ...
基于spring+springMvc+mybatis 开发的企业门户网站基于spring+springMvc+mybatis 开发的企业门户网站基于spring+springMvc+mybatis 开发的企业门户网站基于spring+springMvc+mybatis 开发的企业门户网站基于spring+...
基于Spring+SpringMVC+Mybaits的小区停车场车牌识别系统 基于Spring+SpringMVC+Mybaits的小区停车场车牌识别系统 基于Spring+SpringMVC+Mybaits的小区停车场车牌识别系统 基于Spring+SpringMVC+Mybaits的小区停车场...
基于SSM(Spring+SpringMVC+Mybatis)的新闻管理系统源码+数据库.zip 基于SSM(Spring+SpringMVC+Mybatis)的新闻管理系统源码+数据库.zip 基于SSM(Spring+SpringMVC+Mybatis)的新闻管理系统源码+数据库.zip 基于SSM...
酒店管理系统源码(spring+springmvc+mybatis) 酒店管理系统源码(spring+springmvc+mybatis) 酒店管理系统源码(spring+springmvc+mybatis) 酒店管理系统源码(spring+springmvc+mybatis) 酒店管理系统...