最近项目需要搭建新工程,打算使用微服务的形式搭建便于后期拓展。看了一圈发现springboot易于搭建,配置简单,强化注解功能,"just run"。
Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run". We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.
话不多说,使用maven搭建pom.xml,添加对spring-boot-starter-web的依赖,这样我们就无需设置各个依赖项及其版本信息了。并且在构建中要声明使用spring-boot-maven-plugin这个插件,它会对Maven打包形成的JAR进行二次修改,最终产生符合我们要求的内容结构。
项目结构
添加hibernate依赖,mysql驱动,druid依赖。这里hibernate,mysql并不需要选择版本,添加parent依赖自动为你寻找对应的版本。
<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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jon-spring</groupId> <artifactId>jon-spring-boot</artifactId> <version>0.0.1-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.0.BUILD-SNAPSHOT</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-solr</artifactId> </dependency> --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.20</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <type>jar</type> <scope>compile</scope> </dependency> <!-- <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency> <dependency> <groupId>net.sf.dozer</groupId> <artifactId>dozer</artifactId> <version>5.3.2</version> <type>jar</type> <scope>compile</scope> </dependency> --> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.7</source> <target>1.7</target> <encoding>UTF-8</encoding> <compilerArguments> <extdirs>src/main/webapp/WEB-INF/lib</extdirs> </compilerArguments> </configuration> </plugin> </plugins> </build> <!-- Add Spring repositories --> <!-- (you don't need this if you are using a .RELEASE version) --> <repositories> <repository> <id>spring-snapshots</id> <url>http://repo.spring.io/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>spring-milestones</id> <url>http://repo.spring.io/milestone</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-snapshots</id> <url>http://repo.spring.io/snapshot</url> </pluginRepository> <pluginRepository> <id>spring-milestones</id> <url>http://repo.spring.io/milestone</url> </pluginRepository> </pluginRepositories> </project>
由于springboot强调去XML配置文件,强化注解。druid注入时,使用注解。
package hello.configuration; import javax.sql.DataSource; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.alibaba.druid.pool.DruidDataSource; @Configuration @EnableTransactionManagement public class DataBaseConfiguration implements EnvironmentAware { private RelaxedPropertyResolver propertyResolver; @Override public void setEnvironment(Environment env) { this.propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource."); } @Bean(destroyMethod = "close", initMethod = "init") public DataSource writeDataSource() { System.out.println("注入druid!!!"); DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(propertyResolver.getProperty("url")); datasource.setDriverClassName(propertyResolver.getProperty("driver-class-name")); datasource.setUsername(propertyResolver.getProperty("username")); datasource.setPassword(propertyResolver.getProperty("password")); datasource.setInitialSize(Integer.valueOf(propertyResolver.getProperty("initialSize"))); datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("minIdle"))); datasource.setMaxWait(Long.valueOf(propertyResolver.getProperty("maxWait"))); datasource.setMaxActive(Integer.valueOf(propertyResolver.getProperty("maxActive"))); datasource.setMinEvictableIdleTimeMillis(Long.valueOf(propertyResolver.getProperty("minEvictableIdleTimeMillis"))); return datasource; } }
application.properties配置文件,springboot推荐使用YAML格式作为资源配置文件首选,博主懒,一直用properties文件。项目启动时,会自动读取。
#spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.url=jdbc:mysql://localhost\:3306/stest?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull spring.datasource.username=root spring.datasource.password=root123 spring.datasource.driver-class-name=com.mysql.jdbc.Driver # \u4E0B\u9762\u4E3A\u8FDE\u63A5\u6C60\u7684\u8865\u5145\u8BBE\u7F6E\uFF0C\u5E94\u7528\u5230\u4E0A\u9762\u6240\u6709\u6570\u636E\u6E90\u4E2D # \u521D\u59CB\u5316\u5927\u5C0F\uFF0C\u6700\u5C0F\uFF0C\u6700\u5927 spring.datasource.initialSize=5 spring.datasource.minIdle=5 spring.datasource.maxActive=20 # \u914D\u7F6E\u83B7\u53D6\u8FDE\u63A5\u7B49\u5F85\u8D85\u65F6\u7684\u65F6\u95F4 spring.datasource.maxWait=60000 # \u914D\u7F6E\u95F4\u9694\u591A\u4E45\u624D\u8FDB\u884C\u4E00\u6B21\u68C0\u6D4B\uFF0C\u68C0\u6D4B\u9700\u8981\u5173\u95ED\u7684\u7A7A\u95F2\u8FDE\u63A5\uFF0C\u5355\u4F4D\u662F\u6BEB\u79D2 spring.datasource.timeBetweenEvictionRunsMillis=60000 # \u914D\u7F6E\u4E00\u4E2A\u8FDE\u63A5\u5728\u6C60\u4E2D\u6700\u5C0F\u751F\u5B58\u7684\u65F6\u95F4\uFF0C\u5355\u4F4D\u662F\u6BEB\u79D2 spring.datasource.minEvictableIdleTimeMillis=300000 #\u5B89\u5168\u966A\u4F60 #security.user.name=admin #security.user.password=admin #tomcat\u542F\u52A8\u7AEF\u53E3\u597D #server.port=8089 spring.jpa.hibernate.ddl-auto=update spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext spring.jpa.properties.hibernate.show_sql=true
hibernate配置,为了适配原有项目,需要注入sessionfactory。
package hello.hibernate; import java.io.Serializable; import java.util.List; import java.util.Map; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.criterion.Criterion; import hello.page.PageFinder; /** * hibernate接口 * @author chenlili * * @param <T> */ public interface IHibernateBaseDao<T> { /** * 根据ID获取实体对象. * * @param id * 记录ID * @return 实体对象 */ public T get(Serializable id); /** * 根据ID获取实体对象. * * @param id * 记录ID * @return 实体对象 */ public T load(Serializable id); /** * 根据ID数组获取实体对象集合. * * @param ids * ID对象数组 * * @return 实体对象集合 */ public List<T> get(Serializable[] ids); /** * 根据属性名和属性值获取实体对象. * * @param propertyName * 属性名称 * @param value * 属性值 * @return 实体对象 */ public T get(String propertyName, Object value); /** * 根据属性名和属性值获取实体对象集合. * * @param propertyName * 属性名称 * @param value * 属性值 * @return 实体对象集合 */ public List<T> getList(String propertyName, Object value); /** * @Title: getList * @Description: 根据属性名和属性值数组获取实体对象集合. * @param propertyName * @param values * @return * @throws * @date: 2015-1-9上午10:01:49 */ public List<T> getList(String propertyName, Object[] values); /** * 获取所有实体对象集合. * * @return 实体对象集合 */ public List<T> getAll(); /** * 获取所有实体对象总数. * * @return 实体对象总数 */ public Long getTotalCount(); /** * 根据属性名、修改前后属性值判断在数据库中是否唯一(若新修改的值与原来值相等则直接返回true). * * @param propertyName * 属性名称 * @param oldValue * 修改前的属性值 * @param oldValue * 修改后的属性值 * @return boolean */ public boolean isUnique(String propertyName, Object oldValue, Object newValue); /** * 根据属性名判断数据是否已存在. * * @param propertyName * 属性名称 * @param value * 值 * @return boolean */ public boolean isExist(String propertyName, Object value); /** * 保存实体对象. * * @param entity * 对象 * @return ID */ public Serializable save(T entity); /** * 更新实体对象. * * @param entity * 对象 */ public void update(T entity); /** * 删除实体对象. * * @param entity * 对象 * @return */ public void delete(T entity); /** * 根据ID删除实体对象. * * @param id * 记录ID */ public void delete(Serializable id); /** * 根据ID数组删除实体对象. * * @param ids * ID数组 */ public void delete(Serializable[] ids); /** * * @Title: delete * @Description: 根据指定属性名和值删除记录 * @param propertyName * @param value * @throws * @date: 2015-4-2下午02:07:36 */ public void delete(String propertyName, Object value); public int delete(Map<String, Object> condition) throws Exception; /** * 清除某一对象. * * @param object * 需要清除的对象 */ public void evict(Object object); public void flush(); public void clear(); /** * 保存或更新对象 * * @Title: saveOrUpdate * * @param o * @return 返回保存的对象 * @throws Exception * @throws * @date: 2015-12-17上午11:49:31 */ public T saveOrUpdate(T o); /** * 创建 Criteria * * @Title: createCriteria * * @param criterions * @return * @throws * @date: 2015-12-17下午01:29:46 */ public Criteria createCriteria(Criterion... criterions); /** * 取得Entity的Criteria对象,带排序字段与升降序字段. * * @param orderBy * @param isAsc * @param criterions * @return */ public Criteria createCriteria(String orderBy, boolean isAsc, Criterion... criterions); /** * 获得所有并排序 * * @Title: getAllByOrder * * @param orderBy * @param isAsc * @return * @throws */ public List<T> getAllByOrder(String orderBy, boolean isAsc, boolean useCache); /** * 获得指定条数并排序 * * @Title: getLimitByOrder * * @param orderBy * @param isAsc * @param limit * @return * @throws */ public List<T> getLimitByOrder(String orderBy, boolean isAsc, int limit, boolean useCache); /** * 获得总条数 * * @Title: getRowCount * * @param criteria * @return * @throws */ public int getRowCount(Criteria criteria); /** * @Title: getListByCriteria * @Description: 根据标准查询器,查询数据 * @param criteria * @return * @throws */ public List<T> getListByCriteria(Criteria criteria); /** * 从指定行查询指定条数据 * * @Title: getListByCriteria * * @param criteria * @param fistResult * @param maxResult * @return * @throws */ public List<T> getListByCriteria(Criteria criteria, int fistRow, int rowNum, boolean useCache); /** * 分页查询 * * @Title: pagedByCriteria * * @param criteria * @param pageNo * @param pageSize * @return * @throws */ public PageFinder<T> pagedByCriteria(Criteria criteria, int pageNo, int pageSize); /** * 创建hqlQuery * * @Title: createQuery * * @param hql * @param values * @return * @throws */ public Query createQuery(String hql, Object... values); /** * 创建hqlQuery * * @Title: createQuery * * @param hql * @param values * @return * @throws */ public Query createQuery(String hql, Map<String, ?> values); /** * 创建sqlQuery * * @Title: createSQLQuery * * @param sql * @param values * @return * @throws */ public SQLQuery createSQLQuery(String sql, Object... values); /** * 创建sqlQuery * * @Title: createSQLQuery * * @param sql * @param values * @return * @throws */ public Query createSQLQuery(String sql, Map<String, ?> values); /** * 通过HQL得到一个对象 * * @Title: getObjectByHql * * @param hql * @param values * @return * @throws */ public T getObjectByHql(String hql, Map<String, Object> values); /** * 通过HQL得到一个对象 * * @Title: getObjectByHql * * @param hql * @param values * @return */ public T getObjectByHql(String hql, Object... values); /** * 通过HQL得到查询列表 * * @Title: getListByHql * * @param hql * @param values * @return * @throws */ public List<T> getListByHql(String hql, Map<String, Object> values); /** * 通过HQL得到查询列表 * * @Title: getListByHql * * @param hql * @param values * @return */ public List<T> getListByHql(String hql, Object... values); /** * 通过HQL得到查询列表 * * @Title: getListByHql * * @param hql * @param values * @param firstRow * @param maxNum * @return * @throws */ public List<T> getListByHql(String hql, int firstRow, int maxNum, Map<String, Object> values); /** * 通过HQL得到查询列表 * * @Title: getListByHql * * @param hql * @param firstRow * @param maxNum * @param values * @return */ public List<T> getListByHql(String hql, int firstRow, int maxNum, Object... values); /** * 分页查询:通过HQL,HQL不要包含子查询 * * @Title: pagedByHQL * * @param hql * @param toPage * @param pageSize * @param values * @return * @throws */ public PageFinder<T> pagedByHQL(String hql, int toPage, int pageSize, Map<String, Object> values); /** * 分页查询:通过HQL,HQL不要包含子查询 * * @Title: pagedByHQL * * @param hql * @param toPage * @param pageSize * @param values * @return */ public PageFinder<T> pagedByHQL(String hql, int toPage, int pageSize, Object... values); /** * 定制数据列表查询 * * @Title: getListByHQL * * @param datasql * @param values * @return * @throws */ @SuppressWarnings("rawtypes") public List getListByHQL(String datasql, Map<String, Object> values); /** * 定制数据列表查询 * * @Title: getListByHQL * * @param datasql * @param firstRow * @param maxNum * @param values * @return * @throws */ @SuppressWarnings("rawtypes") public List getListByHQL(String datasql, int firstRow, int maxNum, Map<String, Object> values); /** * 分页定制数据查询 * * @Title: pagedByHQLtoObject * * @param countHql * @param hql * @param toPage * @param pageSize * @param values * @return * @throws */ public PageFinder<Object> pagedObjectByHQL(String countHql, String hql, int toPage, int pageSize, Map<String, Object> values); /** * 通过SQL语句列表查询 * * @Title: getListBySQL * @param datasql * @param values * @return * @throws */ public List<Object> getListBySQL(String datasql, Map<String, Object> values); /** * 通过SQL语句列表查询 * * @Title: getListBySQL * @param datasql * @param firstRow * @param maxNum * @param values * @return * @throws */ public List<Object> getListBySQL(String datasql, int firstRow, int maxNum, Map<String, Object> values); /** * 通过SQL语句分页查询 * * @Title: pagedBySQL * @param countsql * @param datasql * @param toPage * @param pageSize * @param values * @return * @throws */ public PageFinder<Object> pagedObjectBySQL(String countsql, String datasql, int toPage, int pageSize, Map<String, Object> values); }
package hello.hibernate.impl; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Resource; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.lang.StringUtils; import org.hibernate.Criteria; import org.hibernate.NonUniqueResultException; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.hibernate.metadata.ClassMetadata; import org.springframework.util.Assert; import hello.hibernate.IHibernateBaseDao; import hello.page.PageFinder; import hello.utils.ReflectionUtils; public class HibernateBaseDao<T> implements IHibernateBaseDao<T> { private final Class<T> entityClass; @Resource protected SessionFactory sessionFactory; @SuppressWarnings("unchecked") public HibernateBaseDao() { this.entityClass = ReflectionUtils.getSuperClassGenricType(this.getClass(), 0); } public T load(Serializable id) { Assert.notNull(id, "id is required"); return (T) this.getSession().load(this.entityClass, id); } protected void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } protected Session getSession() { return this.sessionFactory.getCurrentSession(); } public T get(Serializable id) { Assert.notNull(id, "id is required"); return (T) this.getSession().get(this.entityClass, id); } @SuppressWarnings("unchecked") public List<T> get(Serializable[] ids) { Assert.notEmpty(ids, "ids must not be empty"); String hql = "from " + this.entityClass.getName() + " as model where model.id in(:ids)"; return this.getSession().createQuery(hql).setParameterList("ids", ids).list(); } @SuppressWarnings("unchecked") public T get(String propertyName, Object value) { // Assert.hasText(propertyName, "propertyName must not be empty"); // Assert.notNull(value, "value is required"); if (value == null) { return null; } String hql = "from " + this.entityClass.getName() + " as model where model." + propertyName + " = ?"; return (T) this.getSession().createQuery(hql).setParameter(0, value).uniqueResult(); } @SuppressWarnings("unchecked") public List<T> getList(String propertyName, Object value) { Assert.hasText(propertyName, "propertyName must not be empty"); Assert.notNull(value, "value is required"); String hql = "from " + this.entityClass.getName() + " as model where model." + propertyName + " = ?"; return this.getSession().createQuery(hql).setParameter(0, value).list(); } @SuppressWarnings("unchecked") public List<T> getList(String propertyName, Object[] values) { Assert.hasText(propertyName, "propertyName must not be empty"); Assert.notNull(values, "values is required"); String hql = "from " + this.entityClass.getName() + " as model where model." + propertyName + " in(:values)"; return this.getSession().createQuery(hql).setParameterList("values", values).list(); } @SuppressWarnings("unchecked") public List<T> getAll() { String hql = "from " + this.entityClass.getName(); return this.getSession().createQuery(hql).list(); } public Long getTotalCount() { String hql = "select count(*) from " + this.entityClass.getName(); return (Long) this.getSession().createQuery(hql).uniqueResult(); } public boolean isUnique(String propertyName, Object oldValue, Object newValue) { Assert.hasText(propertyName, "propertyName must not be empty"); Assert.notNull(newValue, "newValue is required"); if (newValue == oldValue || newValue.equals(oldValue)) { return true; } if (newValue instanceof String) { if (oldValue != null && StringUtils.equalsIgnoreCase((String) oldValue, (String) newValue)) { return true; } } T object = this.get(propertyName, newValue); return object == null; } public boolean isExist(String propertyName, Object value) { Assert.hasText(propertyName, "propertyName must not be empty"); Assert.notNull(value, "value is required"); T object = this.get(propertyName, value); return object != null; } public Serializable save(T entity) { Assert.notNull(entity, "entity is required"); return this.getSession().save(entity); } public void update(T entity) { Assert.notNull(entity, "entity is required"); this.getSession().update(entity); } public T saveOrUpdate(T o) { this.getSession().saveOrUpdate(o); return o; } public void delete(T entity) { Assert.notNull(entity, "entity is required"); this.getSession().delete(entity); } public void delete(Serializable id) { Assert.notNull(id, "id is required"); T entity = this.load(id); this.getSession().delete(entity); } public void delete(Serializable[] ids) { Assert.notEmpty(ids, "ids must not be empty"); for (Serializable id : ids) { T entity = this.load(id); this.getSession().delete(entity); } } public void delete(String propertyName, Object value) { Assert.notNull(propertyName, "propertyName is required"); Assert.notNull(value, "value is required"); String hql = "delete from " + this.entityClass.getName() + " as model where model." + propertyName + " = ?"; this.getSession().createQuery(hql).setParameter(0, value).executeUpdate(); } public int delete(Map<String, Object> conditions) throws Exception { if (null == conditions || conditions.isEmpty()) { throw new Exception("No conditions!"); } StringBuffer hql = new StringBuffer("delete from " + this.entityClass.getName() + " as model "); if (null != conditions && conditions.size() > 0) { hql.append(" where "); int i = 1; Set<String> keySet = conditions.keySet(); for (String key : keySet) { Object value = conditions.get(key); if (i > 1) { hql.append(" AND "); } if (value instanceof Collection<?> || value instanceof Object[]) { hql.append(" model." + key + " IN(:" + key + ") "); } else { hql.append(" model." + key + " = :" + key + " "); } ++i; } } Query createQuery = this.getSession().createQuery(hql.toString()); createQuery = this.setParameter(createQuery, conditions); return createQuery.executeUpdate(); } public void evict(Object object) { Assert.notNull(object, "object is required"); this.getSession().evict(object); } public void flush() { this.getSession().flush(); } public void clear() { this.getSession().clear(); } public Criteria createCriteria(Criterion... criterions) { Criteria criteria = this.getSession().createCriteria(this.entityClass); for (Criterion c : criterions) { criteria.add(c); } return criteria; } public Criteria createCriteria(String orderBy, boolean isAsc, Criterion... criterions) { Criteria criteria = this.createCriteria(criterions); if (isAsc) { criteria.addOrder(Order.asc(orderBy)); } else { criteria.addOrder(Order.desc(orderBy)); } return criteria; } public List<T> getAllByOrder(String orderBy, boolean isAsc, boolean useCache) { return this.getLimitByOrder(orderBy, isAsc, -1, useCache); } @SuppressWarnings("unchecked") public List<T> getLimitByOrder(String orderBy, boolean isAsc, int limit, boolean useCache) { Assert.hasText(orderBy); Order order = isAsc ? Order.asc(orderBy) : Order.desc(orderBy); Criteria criteria = this.createCriteria(); if (limit > 0) { criteria.setMaxResults(limit); } criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).addOrder(order).setCacheable(useCache); return criteria.list(); } public int getRowCount(Criteria criteria) { criteria.setProjection(Projections.rowCount()); Long totalRows = (Long) criteria.uniqueResult(); return totalRows.intValue(); } @SuppressWarnings("unchecked") public List<T> getListByCriteria(Criteria criteria) { criteria = criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return criteria.list(); } @SuppressWarnings("unchecked") public List<T> getListByCriteria(Criteria criteria, int fistRow, int rowNum, boolean useCache) { criteria = criteria.setFirstResult(fistRow).setMaxResults(rowNum).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).setCacheable(useCache); return criteria.list(); } public PageFinder<T> pagedByCriteria(Criteria criteria, int pageNo, int pageSize) { int totalRows = this.getRowCount(criteria); criteria.setProjection(null); if (totalRows < 1) { PageFinder<T> finder = new PageFinder<T>(pageNo, pageSize, totalRows); finder.setData(new ArrayList<T>()); return finder; } else { PageFinder<T> finder = new PageFinder<T>(pageNo, pageSize, totalRows); List<T> list = this.getListByCriteria(criteria, finder.getStartOfPage(), finder.getPageSize(), false); finder.setData(list); return finder; } } public Query createQuery(String hql, Object... values) { Assert.hasText(hql, "sql 不能为空"); Query query = this.getSession().createQuery(hql); if (values != null) { for (int i = 0; i < values.length; i++) { query.setParameter(i, values[i]); } } return query; } public Query createQuery(String hql, Map<String, ?> values) { Assert.hasText(hql, "sql 不能为空"); Query query = this.createQuery(hql); if (values != null) { query = this.setParameter(query, values); } return query; } @SuppressWarnings("unchecked") public T getObjectByHql(String hql, Map<String, Object> values) { Query query = this.createQuery(hql, values); return (T) query.uniqueResult(); } @SuppressWarnings("unchecked") public List<T> getListByHql(String hql, Map<String, Object> values) { Query query = this.createQuery(hql); query = this.setParameter(query, values); return query.list(); } @SuppressWarnings("unchecked") public List<T> getListByHql(String hql, int firstRow, int maxNum, Map<String, Object> values) { Query query = this.createQuery(hql); query = this.setParameter(query, values); query.setFirstResult(firstRow); query.setMaxResults(maxNum); return query.list(); } public PageFinder<T> pagedByHQL(String hql, int toPage, int pageSize, Map<String, Object> values) { String countQueryString = " select count(*) " + this.removeSelect(this.removeOrders(hql)); List<T> countlist = this.getListByHql(countQueryString, values); Long totalCount = (Long) countlist.get(0); if (totalCount.intValue() < 1) { return new PageFinder<T>(toPage, pageSize, totalCount.intValue()); } else { final PageFinder<T> finder = new PageFinder<T>(toPage, pageSize, totalCount.intValue()); List<T> list = this.getListByHql(hql, finder.getStartOfPage(), finder.getPageSize(), values); finder.setData(list); return finder; } } @SuppressWarnings("rawtypes") public List getListByHQL(String datasql, Map<String, Object> values) { Query dataQuery = this.createQuery(datasql, values); return dataQuery.list(); } @SuppressWarnings("rawtypes") public List getListByHQL(String datasql, int firstRow, int maxNum, Map<String, Object> values) { Query dataQuery = this.createQuery(datasql, values); dataQuery.setFirstResult(firstRow); dataQuery.setMaxResults(maxNum); return dataQuery.list(); } @SuppressWarnings("unchecked") public PageFinder<Object> pagedObjectByHQL(String countHql, String hql, int toPage, int pageSize, Map<String, Object> values) { Query query = this.createQuery(countHql, values); Long totalCount = (Long) query.uniqueResult(); if (totalCount.intValue() < 1) { return new PageFinder<Object>(toPage, pageSize, totalCount.intValue()); } else { PageFinder<Object> finder = new PageFinder<Object>(toPage, pageSize, totalCount.intValue()); List<Object> list = this.getListByHQL(hql, finder.getStartOfPage(), finder.getPageSize(), values); finder.setData(list); return finder; } } @SuppressWarnings("unchecked") public T getObjectByHql(String hql, Object... values) { Query query = this.createQuery(hql, values); List<T> list = query.list(); if (null != list && list.size() > 0) { T first = list.get(0); for (int i = 1; i < list.size(); i++) { if (list.get(i) != first) { throw new NonUniqueResultException(list.size()); } } return first; } return null; } @SuppressWarnings("unchecked") public List<T> getListByHql(String hql, Object... values) { Query dataQuery = this.createQuery(hql, values); return dataQuery.list(); } @SuppressWarnings("unchecked") public List<T> getListByHql(String hql, int firstRow, int maxNum, Object... values) { Query query = this.createQuery(hql, values); query.setFirstResult(firstRow); query.setMaxResults(maxNum); return query.list(); } public PageFinder<T> pagedByHQL(String hql, int toPage, int pageSize, Object... values) { String countQueryString = " select count(*) " + this.removeSelect(this.removeOrders(hql)); List<T> countlist = this.getListByHql(countQueryString, values); Long totalCount = (Long) countlist.get(0); if (totalCount.intValue() < 1) { return new PageFinder<T>(toPage, pageSize, totalCount.intValue()); } else { final PageFinder<T> finder = new PageFinder<T>(toPage, pageSize, totalCount.intValue()); List<T> list = this.getListByHql(hql, finder.getStartOfPage(), finder.getPageSize(), values); finder.setData(list); return finder; } } public SQLQuery createSQLQuery(String sql, Object... values) { Assert.hasText(sql, "sql 不能为空"); SQLQuery query = this.getSession().createSQLQuery(sql); if (values != null) { for (int i = 0; i < values.length; i++) { query.setParameter(i, values[i]); } } return query; } public SQLQuery createSQLQuery(String sql, Map<String, ?> values) { Assert.hasText(sql, "sql 不能为空"); Query query = this.createSQLQuery(sql); if (values != null) { query = this.setParameter(query, values); } return (SQLQuery) query; } @SuppressWarnings("unchecked") public List<Object> getListBySQL(String datasql, Map<String, Object> values) { SQLQuery dataQuery = this.createSQLQuery(datasql, values); return dataQuery.list(); } @SuppressWarnings("unchecked") public List<Object> getListBySQL(String datasql, int firstRow, int maxNum, Map<String, Object> values) { SQLQuery dataQuery = this.createSQLQuery(datasql, values); dataQuery.setFirstResult(firstRow); dataQuery.setMaxResults(maxNum); return dataQuery.list(); } public PageFinder<Object> pagedObjectBySQL(String countsql, String datasql, int toPage, int pageSize, Map<String, Object> values) { SQLQuery query = this.createSQLQuery(countsql, values); Long totalCount = Long.parseLong(query.uniqueResult().toString()); if (totalCount.intValue() < 1) { return new PageFinder<Object>(toPage, pageSize, totalCount.intValue()); } else { PageFinder<Object> finder = new PageFinder<Object>(toPage, pageSize, totalCount.intValue()); List<Object> list = this.getListBySQL(datasql, finder.getStartOfPage(), finder.getPageSize(), values); finder.setData(list); return finder; } } /** * 取得对象的主键值,辅助函数. */ @SuppressWarnings("unused") private Serializable getId(Object entity) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Assert.notNull(entity); return (Serializable) PropertyUtils.getProperty(entity, this.getIdName()); } /** * 取得对象的主键名,辅助函数. */ private String getIdName() { ClassMetadata meta = this.sessionFactory.getClassMetadata(this.entityClass); Assert.notNull(meta, "Class " + this.entityClass + " not define in hibernate session factory."); String idName = meta.getIdentifierPropertyName(); Assert.hasText(idName, this.entityClass.getSimpleName() + " has no identifier property define."); return idName; } /** * hql 设置参数 * * @Title: setParameter * @Description: TODO * @param query * @param map * @return * @throws * @author: yong * @date: 2012-12-17下午05:56:15 */ private Query setParameter(Query query, Map<String, ?> map) { if (map != null && !map.isEmpty()) { Set<String> keySet = map.keySet(); for (String string : keySet) { Object obj = map.get(string); // 这里考虑传入的参数是什么类型,不同类型使用的方法不同 if (obj instanceof Collection<?>) { query.setParameterList(string, (Collection<?>) obj); } else if (obj instanceof Object[]) { query.setParameterList(string, (Object[]) obj); } else { query.setParameter(string, obj); } } } return query; } /** * 去除hql的select 子句,未考虑union的情况用于pagedQuery. * * @param hql * @return */ private String removeSelect(String hql) { Assert.hasText(hql); int beginPos = hql.toLowerCase().indexOf("from"); Assert.isTrue(beginPos != -1, " hql : " + hql + " must has a keyword 'from'"); return hql.substring(beginPos); } /** * 去除hql的orderby 子句,用于pagedQuery. * * @param hql * @return */ private String removeOrders(String hql) { Assert.hasText(hql); Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(hql); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, ""); } m.appendTail(sb); return sb.toString(); } }
分页工具类PageFinder.java
package hello.page; import java.io.Serializable; import java.util.List; import java.util.Map; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * 分页对象. 包含当前页数据及分页信息 * */ @SuppressWarnings("serial") public class PageFinder<T> implements Serializable { public final static int DEFAULT_PAGE_SIZE = 10; /** * 每页的记录数 */ private int pageSize = DEFAULT_PAGE_SIZE; /** * 当前页中存放的数据 */ @Expose @SerializedName("rows") private List<T> data; /** * 总记录数 */ @Expose @SerializedName("total") private int rowCount; /** * 页数 */ @Expose @SerializedName("page") private int pageCount; /** * 跳转页数 */ private int pageNo; /** * 是否有上一页 */ private boolean hasPrevious = false; /** * 是否有下一页 */ private boolean hasNext = false; /** * 表格页脚数据 */ @Expose @SerializedName("footer") private List<Map<String, Object>> footers; public PageFinder() { } public PageFinder(int pageNo, int rowCount) { this.pageNo = pageNo; this.rowCount = rowCount; this.pageCount = getTotalPageCount(); refresh(); } /** * 构造方法 */ public PageFinder(int pageNo, int pageSize, int rowCount) { this.pageNo = pageNo; this.pageSize = pageSize; this.rowCount = rowCount; this.pageCount = getTotalPageCount(); refresh(); } public PageFinder(int pageNo, int pageSize, int rowCount, List<T> data) { this.pageNo = pageNo; this.pageSize = pageSize; this.rowCount = rowCount; this.pageCount = getTotalPageCount(); this.data = data; refresh(); } /** * 取总页数 */ private final int getTotalPageCount() { if (rowCount % pageSize == 0) return rowCount / pageSize; else return rowCount / pageSize + 1; } /** * 刷新当前分页对象数据 */ private void refresh() { if (pageCount <= 1) { hasPrevious = false; hasNext = false; } else if (pageNo == 1) { hasPrevious = false; hasNext = true; } else if (pageNo == pageCount) { hasPrevious = true; hasNext = false; } else { hasPrevious = true; hasNext = true; } } /** * 取每页数据数 */ public int getPageSize() { return pageSize; } /** * 取当前页中的记录. */ public Object getResult() { return data; } public List<T> getData() { return data; } public void setData(List<T> data) { this.data = data; } public int getRowCount() { return rowCount; } public void setRowCount(int rowCount) { this.rowCount = rowCount; } public int getPageCount() { return pageCount; } public void setPageCount(int pageCount) { this.pageCount = pageCount; } public int getPageNo() { return pageNo; } public void setPageNo(int pageNo) { this.pageNo = pageNo; } public boolean isHasPrevious() { return hasPrevious; } public void setHasPrevious(boolean hasPrevious) { this.hasPrevious = hasPrevious; } public boolean isHasNext() { return hasNext; } public void setHasNext(boolean hasNext) { this.hasNext = hasNext; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public List<Map<String, Object>> getFooters() { return footers; } public void setFooters(List<Map<String, Object>> footers) { this.footers = footers; } /** * 获取跳转页第一条数据在数据集的位置 */ public int getStartOfPage() { return ((pageNo - 1)<0?0:pageNo) * pageSize; } }
驱动类Application.java
package hello; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } /** * 注入sessionfatory * @return */ @Bean public HibernateJpaSessionFactoryBean sessionFactory() { return new HibernateJpaSessionFactoryBean(); } }
此时sessionfactory注入成功。