使用druid-spring-boot-starter 提供的配置方法,运行之后应用不到druid连接处,而是默认的HikariPool
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.druid</groupId>
<artifactId>druid</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>druid</name>
<description>测试</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
运行的类
package com.druid;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages="com.alibaba.druid.spring.boot")
public class DruidApplication {
public static void main(String[] args) {
SpringApplication.run(DruidApplication.class, args);
}
}
参考 配置进行详细的对比:https://blog.csdn.net/u010513756/article/details/80235876
问题我自己已经解决了,是druid版本问题 ,如果用的druid-spring-boot-starter版本为1.1.10 ,那么搭配的druid版本要是1.1.9,其他版本我不知道,但用1.1.10的druid就肯定会出现我上面说的问题,;
现在网上搜索springboot +druid 都是要我们写一堆代码,其实大家可以用druid-spring-boot-starter去做,不用写一句代码,只要配置下就可以了,而且还支持多数据库配置,参考https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter
最后附上pom.xml中druid的配置,
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
控制台一直都打印是:
Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
application:
# 只有下面三个是必填项(使用内嵌数据库的话这三个也可以不用填,会使用默认配置),其他配置不是必须的
spring.datasource.url=jdbc:h2:file:./demo-db
spring.datasource.username=sa
spring.datasource.password=sa
# driver-class-name 非必填可根据url推断
spring.datasource.driver-class-name=org.h2.Driver
#Druid 数据源配置,继承spring.datasource.* 配置,相同则覆盖
spring.datasource.druid.initial-size=2
spring.datasource.druid.max-active=30
spring.datasource.druid.min-idle=2
spring.datasource.druid.max-wait=1234
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=5
#spring.datasource.druid.max-open-prepared-statements= #等价于上面的max-pool-prepared-statement-per-connection-size
spring.datasource.druid.validation-query=select 1
spring.datasource.druid.validation-query-timeout=1
spring.datasource.druid.test-on-borrow=true
spring.datasource.druid.test-on-return=true
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.time-between-eviction-runs-millis=10000
spring.datasource.druid.min-evictable-idle-time-millis=30001
spring.datasource.druid.async-close-connection-enable=true
spring.datasource.druid.aop-patterns=com.alibaba.druid.spring.boot.demo.service.*
# 自定义StatFilter 配置 其他 Filter 不再演示
spring.datasource.druid.filter.stat.db-type=h2
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.filter.stat.slow-sql-millis=2000
# JPA
spring.jpa.show-sql= true
spring.jpa.hibernate.ddl-auto=create-drop
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource, 加上这一句试试。
添加hibernate依赖,mysql驱动,druid依赖。这里hibernate,mysql并不需要选择版本,添加parent依赖自动为你寻找对应的版本。
复制代码
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.jon-spring
jon-spring-boot
0.0.1-SNAPSHOT
<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>
复制代码
由于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
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
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;
/**
@param
*/
public interface IHibernateBaseDao {
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
public int delete(Map condition) throws Exception;
/**
public void flush();
public void clear();
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
}
复制代码
复制代码
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 implements IHibernateBaseDao {
private final Class 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 implements Serializable {
public final static int DEFAULT_PAGE_SIZE = 10;
/**
/**
/**
/**
@Expose
@SerializedName("page")
private int pageCount;
/**
/**
/**
/**
@Expose
@SerializedName("footer")
private List> 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, List data) {
this.pageNo = pageNo;
this.pageSize = pageSize;
this.rowCount = rowCount;
this.pageCount = getTotalPageCount();
this.data = data;
refresh();
}
/**
/**
/**
/**
public List getData() {
return data;
}
public void setData(List 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> getFooters() {
return footers;
}
public void setFooters(List> footers) {
this.footers = footers;
}
/**
复制代码
驱动类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注入成功。
在springboot配置文件下制定配置文件
用下面制定使用druid连接池
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
再次启动尝试
查看这篇文章:springboot2集成druid连接池,https://www.jianshu.com/p/170c34bf86a3