org.hibernate.util.PropertiesHelper

本文介绍Hibernate3中用于处理属性文件取值的工具类PropertiesHelper。该类为final且仅包含只读方法,确保线程安全。文章详细展示了如何通过默认值处理配置文件中不存在的属性,并提供了多种数据类型的获取方法。

该类为hibernate3处理属性文件取值的工具类,首先该类是一个final类,且只有private构造函数,即使用者没法继承该类

另外该类的所有方法为只读方法,没有写方法,所以该类又是一个线程安全类,多线程可以放心使用该类,不会出现资源竞争问题

 

该类取值模式值得借鉴,通过传入一个默认值,如果取不到,则直接返回默认值

 

 


package org.hibernate.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Iterator;


public final class PropertiesHelper {

 private static final String PLACEHOLDER_START = "${";
 private static final String PLACEHOLDER_END = "}";

 public static boolean getBoolean(String property, Properties properties) {
  String setting = properties.getProperty(property);
  return setting != null && Boolean.valueOf( setting.trim() ).booleanValue();
 }

 public static boolean getBoolean(String property, Properties properties, boolean defaultValue) {
  String setting = properties.getProperty(property);
  return setting==null ? defaultValue : Boolean.valueOf( setting.trim() ).booleanValue();
 }

 public static int getInt(String property, Properties properties, int defaultValue) {
  String propValue = properties.getProperty(property);
  return propValue==null ? defaultValue : Integer.parseInt( propValue.trim() );
 }

 public static String getString(String property, Properties properties, String defaultValue) {
  String propValue = properties.getProperty(property);
  return propValue==null ? defaultValue : propValue;
 }

 public static Integer getInteger(String property, Properties properties) {
  String propValue = properties.getProperty(property);
  return propValue==null ? null : Integer.valueOf( propValue.trim() );
 }

 public static Map toMap(String property, String delim, Properties properties) {
  Map map = new HashMap();
  String propValue = properties.getProperty(property);
  if (propValue!=null) {
   StringTokenizer tokens = new StringTokenizer(propValue, delim);
   while ( tokens.hasMoreTokens() ) {
    map.put(
     tokens.nextToken(),
        tokens.hasMoreElements() ? tokens.nextToken() : ""
    );
   }
  }
  return map;
 }

 public static String[] toStringArray(String property, String delim, Properties properties) {
  return toStringArray( properties.getProperty(property), delim );
 }

 public static String[] toStringArray(String propValue, String delim) {
  if (propValue!=null) {
   return StringHelper.split(delim, propValue);
  }
  else {
   return ArrayHelper.EMPTY_STRING_ARRAY;
  }
 }

 /**
  * replace a property by a starred version
  *
  * @param props properties to check
  * @param key proeprty to mask
  * @return cloned and masked properties
  */
 public static Properties maskOut(Properties props, String key) {
  Properties clone = (Properties) props.clone();
  if (clone.get(key) != null) {
   clone.setProperty(key, "****");
  }
  return clone;
 }

 public static void resolvePlaceHolders(Properties properties) {
  Iterator itr = properties.entrySet().iterator();
  while ( itr.hasNext() ) {
   final Map.Entry entry = ( Map.Entry ) itr.next();
   final String value = ( String ) entry.getValue();
   if ( value != null ) {
    final String resolved = resolvePlaceHolder( value );
    if ( !value.equals( resolved ) ) {
     if ( resolved == null ) {
      itr.remove();
     }
     else {
      entry.setValue( resolved );
     }
    }
   }
  }
 }

 public static String resolvePlaceHolder(String property) {
  if ( property.indexOf( PLACEHOLDER_START ) < 0 ) {
   return property;
  }
  StringBuffer buff = new StringBuffer();
  char[] chars = property.toCharArray();
  for ( int pos = 0; pos < chars.length; pos++ ) {
   if ( chars[pos] == '$' ) {
    // peek ahead
    if ( chars[pos+1] == '{' ) {
     // we have a placeholder, spin forward till we find the end
     String systemPropertyName = "";
     int x = pos + 2;
     for (  ; x < chars.length && chars[x] != '}'; x++ ) {
      systemPropertyName += chars[x];
      // if we reach the end of the string w/o finding the
      // matching end, that is an exception
      if ( x == chars.length - 1 ) {
       throw new IllegalArgumentException( "unmatched placeholder start [" + property + "]" );
      }
     }
     String systemProperty = extractFromSystem( systemPropertyName );
     buff.append( systemProperty == null ? "" : systemProperty );
     pos = x + 1;
     // make sure spinning forward did not put us past the end of the buffer...
     if ( pos >= chars.length ) {
      break;
     }
    }
   }
   buff.append( chars[pos] );
  }
  String rtn = buff.toString();
  return StringHelper.isEmpty( rtn ) ? null : rtn;
 }

 private static String extractFromSystem(String systemPropertyName) {
  try {
   return System.getProperty( systemPropertyName );
  }
  catch( Throwable t ) {
   return null;
  }
 }

 

 /*私有构造函数,一般单例模式使用私有构造函数*/
 private PropertiesHelper() {}
}

`java.lang.NullPointerException` 是 Java 中常见的异常,当应用程序试图在需要对象的地方使用 `null` 时抛出。异常位置在 `org.hibernate.hql.ast.util.SessionFactoryHelper.findSQLFunction(SessionFactoryHelper.java:364)` 通常意味着在该方法中某个对象为 `null`,而代码尝试对其进行操作。以下是一些可能的解决方法: ### 检查 Hibernate 配置 确保 Hibernate 的配置文件(如 `hibernate.cfg.xml` 或 Spring Boot 中的 `application.properties`/`application.yml`)正确配置。错误的配置可能导致 `SessionFactory` 或相关对象未正确初始化,从而引发 `NullPointerException`。 ```properties # application.properties 示例 spring.datasource.url=jdbc:mysql://localhost:3306/yourdb spring.datasource.username=yourusername spring.datasource.password=yourpassword spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true ``` ### 检查 SQL 函数注册 `findSQLFunction` 方法通常用于查找 SQL 函数。确保所有自定义的 SQL 函数都已正确注册到 Hibernate 中。可以通过实现 `org.hibernate.dialect.Dialect` 并重写 `registerFunctions` 方法来注册自定义函数。 ```java import org.hibernate.dialect.MySQL8Dialect; import org.hibernate.dialect.function.SQLFunctionTemplate; import org.hibernate.type.StandardBasicTypes; public class CustomMySQLDialect extends MySQL8Dialect { public CustomMySQLDialect() { super(); registerFunction("custom_function", new SQLFunctionTemplate(StandardBasicTypes.STRING, "custom_function(?1)")); } } ``` 然后在配置文件中指定自定义方言: ```properties spring.jpa.database-platform=com.example.CustomMySQLDialect ``` ### 确保 SessionFactory 正确初始化 在使用 Hibernate 时,`SessionFactory` 必须正确初始化。在 Spring Boot 中,通常会自动配置 `SessionFactory`,但也需要确保依赖注入正确。 ```java import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class MyService { private final SessionFactory sessionFactory; @Autowired public MyService(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } // 使用 SessionFactory 的方法 } ``` ### 调试和日志记录 在 `SessionFactoryHelper.findSQLFunction` 方法附近添加调试日志,输出可能为 `null` 的对象,以便确定具体是哪个对象为 `null`。 ```java import org.slf4j.Logger; import org.slf4j.LoggerFactory; // 在 SessionFactoryHelper 类中添加日志记录 private static final Logger logger = LoggerFactory.getLogger(SessionFactoryHelper.class); public SQLFunction findSQLFunction(String name) { // 检查可能为 null 的对象 if (someObject == null) { logger.error("someObject is null"); } // 其他代码 } ``` ### 检查依赖版本 确保 Hibernate 及其相关依赖的版本兼容。不兼容的版本可能导致类初始化失败或对象未正确创建。可以通过 Maven 或 Gradle 管理依赖版本。 ```xml <!-- pom.xml 示例 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.6.10.Final</version> </dependency> ``` ### 检查数据库连接 确保数据库服务正在运行,并且应用程序可以正常连接到数据库。可以使用数据库管理工具(如 MySQL Workbench)测试数据库连接。 ### 检查代码逻辑 检查调用 `findSQLFunction` 方法的代码逻辑,确保传递的参数不为 `null`。 ```java // 示例代码 String functionName = getFunctionName(); if (functionName != null) { SQLFunction function = sessionFactoryHelper.findSQLFunction(functionName); // 处理函数 } ``` ### 检查 HQL 查询 如果异常是在执行 HQL 查询时抛出的,检查 HQL 查询语句是否正确,是否包含未定义的 SQL 函数。 ```java // 示例 HQL 查询 String hql = "SELECT custom_function(column) FROM Entity"; Query query = session.createQuery(hql); List result = query.list(); ``` ### 检查事务管理 确保事务管理正确配置。不正确的事务管理可能导致 `Session` 或 `SessionFactory` 未正确初始化或关闭。 ```java import org.springframework.transaction.annotation.Transactional; @Service public class MyService { @Transactional public void doSomething() { // 业务逻辑 } } ``` ### 检查第三方库 如果使用了第三方库,确保这些库与 Hibernate 兼容。不兼容的第三方库可能会干扰 Hibernate 的正常运行。 ### 检查服务器环境 确保服务器环境(如 Java 版本、服务器配置等)符合应用程序的要求。 ### 检查数据库权限 确保应用程序使用的数据库用户具有执行相关 SQL 函数的权限。 ### 检查缓存 如果使用了 Hibernate 的二级缓存,确保缓存配置正确。错误的缓存配置可能导致对象未正确加载,从而引发 `NullPointerException`。 ### 检查代码中的空指针 在调用 `findSQLFunction` 方法之前,确保传递的参数不为 `null`。可以使用 `Objects.requireNonNull` 方法进行检查。 ```java import java.util.Objects; public SQLFunction findSQLFunction(String name) { Objects.requireNonNull(name, "Function name cannot be null"); // 其他代码 } ``` ### 检查数据库表结构 确保数据库表结构与实体类定义一致。不一致的表结构可能导致 Hibernate 在查询时出现问题。 ### 检查数据源配置 确保数据源配置正确,包括数据库连接 URL、用户名、密码等。 ```properties # application.properties 示例 spring.datasource.url=jdbc:mysql://localhost:3306/yourdb spring.datasource.username=yourusername spring.datasource.password=yourpassword ``` ### 检查 Hibernate 版本兼容性 确保 Hibernate 版本与其他依赖库(如 Spring Boot、JDBC 驱动等)兼容。 ### 检查数据库驱动 确保使用的数据库驱动版本与数据库版本兼容。 ```xml <!-- pom.xml 示例 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency> ``` ### 检查 SQL 函数定义 确保 SQL 函数在数据库中正确定义。可以使用数据库管理工具(如 MySQL Workbench)检查函数定义。 ### 检查 Hibernate 日志 启用 Hibernate 的详细日志记录,查看更详细的错误信息。 ```properties # application.properties 示例 logging.level.org.hibernate=DEBUG ``` 通过以上步骤,可以逐步排查并解决 `java.lang.NullPointerException` 异常。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值