Hibernate使用Druid连接池
阅读原文时间:2021年04月20日阅读:1
  1. 源码分析
    (1)DruidDataSourceFactory源码

    public final static String    PROP_PASSWORD   = "password";
    public final static String    PROP_URL        = "url";
    public final static String    PROP_USERNAME   = "username";

    从上面的代码中可以看出Druid获取数据库的字段是没有前缀的
    (2)Hibernate的源码

        public static final String URL ="hibernate.connection.url";
    /**
     * Names the connection user.  This might mean one of 2 things in out-of-the-box Hibernate
     * {@link org.hibernate.service.jdbc.connections.spi.ConnectionProvider}: <ul>
     *     <li>The username used to pass along to creating the JDBC connection</li>
     *     <li>The username used to obtain a JDBC connection from a data source</li>
     * </ul>
     */
    public static final String USER ="hibernate.connection.username";
    
    /**
     * Names the connection password.  See usage discussion on {@link #USER}
     */
    public static final String PASS ="hibernate.connection.password";</code></pre>

    Hibernate的数据库配置信息是有hibernate.connection前缀的,所以当使用Druid是要注意property的转换

  2. 修改Hibernate数据库配置文件

    <property name="connection.provider_class">posp.tools.DruidConnectionProvider</property>#Druid连接池的Hibernate辅助类
    <property name="url"></property>  
    <property name="username"></property>
    <property name="password"></property>
  3. 修改Druid辅助类的configure方法

    配置文件
    <property name="connection.provider_class">posp.tools.DruidConnectionProvider</property>#Druid连接池的Hibernate辅助类
    <property name="hibernate.connection.url"></property>  
    <property name="hibernate.connection.username"></property>
    <property name="hibernate.connection.password"></property>
    辅助类
    public void configure(Map props) {
            String userName = (String) props.get(Environment.USER);
            String password = (String) props.get(Environment.PASS);
            String url = (String) props.get(Environment.URL);
            try {
                //在这里可以对数据库连接信息解密
                super.configure(props);
            } catch (Exception e) {
                e.printStackTrace();
            }
    }

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章