xiaohua914
mmp~7
采纳率100%
2018-06-21 11:37 阅读 8.4k
已采纳

springboot+druid配置无效

5

使用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);
    }
}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

8条回答 默认 最新

  • 已采纳
    weixin_38652136 邪恶八进制 2018-06-22 04:51
    点赞 评论 复制链接分享
  • xiaohua914 mmp~7 2018-06-22 08:33

    问题我自己已经解决了,是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>
    
    点赞 1 评论 复制链接分享
  • xiaohua914 mmp~7 2018-06-21 11:38

    控制台一直都打印是:

     Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
    
    点赞 评论 复制链接分享
  • xiaohua914 mmp~7 2018-06-21 11:41

    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
    
    
    点赞 评论 复制链接分享
  • gf0515 Fatal Error 2018-06-22 00:56

    spring.datasource.type=com.alibaba.druid.pool.DruidDataSource, 加上这一句试试。

    点赞 评论 复制链接分享
  • weixin_42463631 weixin_42463631 2018-06-22 01:10

     添加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

    \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
      */
      public interface IHibernateBaseDao {

      /**

      • 根据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 get(Serializable[] ids);

      /**

      • 根据属性名和属性值获取实体对象.
      • @param propertyName
      • 属性名称
      • @param value
      • 属性值
      • @return 实体对象 */ public T get(String propertyName, Object value);

      /**

      • 根据属性名和属性值获取实体对象集合.
      • @param propertyName
      • 属性名称
      • @param value
      • 属性值
      • @return 实体对象集合 */ public List getList(String propertyName, Object value);

      /**

      • @Title: getList
      • @Description: 根据属性名和属性值数组获取实体对象集合.
      • @param propertyName
      • @param values
      • @return
      • @throws
      • @date: 2015-1-9上午10:01:49 */ public List getList(String propertyName, Object[] values);

      /**

      • 获取所有实体对象集合.
      • @return 实体对象集合 */ public List 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 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 getAllByOrder(String orderBy, boolean isAsc, boolean useCache);

      /**

      • 获得指定条数并排序
      • @Title: getLimitByOrder
      • @param orderBy
      • @param isAsc
      • @param limit
      • @return
      • @throws */ public List 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 getListByCriteria(Criteria criteria);

      /**

      • 从指定行查询指定条数据
      • @Title: getListByCriteria
      • @param criteria
      • @param fistResult
      • @param maxResult
      • @return
      • @throws */ public List getListByCriteria(Criteria criteria, int fistRow, int rowNum, boolean useCache);

      /**

      • 分页查询
      • @Title: pagedByCriteria
      • @param criteria
      • @param pageNo
      • @param pageSize
      • @return
      • @throws */ public PageFinder 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 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 values);

      /**

      • 通过HQL得到一个对象
      • @Title: getObjectByHql
      • @param hql
      • @param values
      • @return
      • @throws */ public T getObjectByHql(String hql, Map 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 getListByHql(String hql, Map values);

      /**

      • 通过HQL得到查询列表
      • @Title: getListByHql
      • @param hql
      • @param values
      • @return */ public List getListByHql(String hql, Object... values);

      /**

      • 通过HQL得到查询列表
      • @Title: getListByHql
      • @param hql
      • @param values
      • @param firstRow
      • @param maxNum
      • @return
      • @throws */ public List getListByHql(String hql, int firstRow, int maxNum, Map values);

      /**

      • 通过HQL得到查询列表
      • @Title: getListByHql
      • @param hql
      • @param firstRow
      • @param maxNum
      • @param values
      • @return */ public List 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 pagedByHQL(String hql, int toPage, int pageSize, Map values);

      /**

      • 分页查询:通过HQL,HQL不要包含子查询
      • @Title: pagedByHQL
      • @param hql
      • @param toPage
      • @param pageSize
      • @param values
      • @return */ public PageFinder 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 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 values);

      /**

      • 分页定制数据查询
      • @Title: pagedByHQLtoObject
      • @param countHql
      • @param hql
      • @param toPage
      • @param pageSize
      • @param values
      • @return
      • @throws */ public PageFinder pagedObjectByHQL(String countHql, String hql, int toPage, int pageSize, Map values);

      /**

      • 通过SQL语句列表查询
      • @Title: getListBySQL
      • @param datasql
      • @param values
      • @return
      • @throws */ public List getListBySQL(String datasql, Map values);

      /**

      • 通过SQL语句列表查询
      • @Title: getListBySQL
      • @param datasql
      • @param firstRow
      • @param maxNum
      • @param values
      • @return
      • @throws */ public List getListBySQL(String datasql, int firstRow, int maxNum, Map values);

      /**

      • 通过SQL语句分页查询
      • @Title: pagedBySQL
      • @param countsql
      • @param datasql
      • @param toPage
      • @param pageSize
      • @param values
      • @return
      • @throws */ public PageFinder pagedObjectBySQL(String countsql, String datasql, int toPage, int pageSize, Map 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 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;

      /**

      • 每页的记录数 */ private int pageSize = DEFAULT_PAGE_SIZE;

      /**

      • 当前页中存放的数据 */ @Expose @SerializedName("rows") private List 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> 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 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 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;
      }

      /**

      • 获取跳转页第一条数据在数据集的位置 */ 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注入成功。

    点赞 评论 复制链接分享
  • boflybofly boflybofly 2018-06-22 02:54

    在springboot配置文件下制定配置文件
    用下面制定使用druid连接池
    spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    再次启动尝试

    点赞 评论 复制链接分享
  • cliseallen allen1683 2019-08-07 14:07

    查看这篇文章:springboot2集成druid连接池,https://www.jianshu.com/p/170c34bf86a3

    点赞 评论 复制链接分享

相关推荐