JPA-Hibernate persistence.xml 对数据库帐号密码进行加密

1、META-INF 下的 persistence.xml


 org.hibernate.ejb.HibernatePersistence
  
   
   
   
   
   	
   																  
         
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
  

2、新建class NewConnectionProvider.java

package com.regaltec.common.hibernate;

import java.util.Properties;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.cfg.Environment;
import org.hibernate.connection.DriverManagerConnectionProvider;

import com.regaltec.esa.common.utils.EncryptUtil;

public class NewConnectionProvider extends DriverManagerConnectionProvider {
	public static final Logger log = LogManager.getLogger(NewConnectionProvider.class);

	public NewConnectionProvider() {
		super();
	}

	@Override
	public void configure(Properties props) throws HibernateException {
		//String user = props.getProperty(Environment.USER);
		String password = props.getProperty(Environment.PASS);
		try {
			//props.setProperty(Environment.USER, EncryptUtil.decrypt(user));
			//System.out.println("解密前密码为:" + password);
			password = EncryptUtil.decrypt(password);
			props.setProperty(Environment.PASS, password);
			//System.out.println("解密后密码为:" + password);
		} catch (Exception e) {
			log.error("解密数据库帐号密码异常:" + e.getMessage(), e);
		}
		super.configure(props);
	}
}

其中 EncryptUtil 是加密、解密的工具类,可自行编写

你可能感兴趣的:(Java,JPA,hibernate)