DAO数据库操作类实现在配置文件中的工厂化管理
一、搭建 Hibernate 环境
二、创建数据库操作接口和实现类
<!--[if !supportLists]-->1、 <!--[endif]-->接口
基类接口(所有接口都继承该接口):
package fr.itris.glips.dbconn.module.dao;
import java.io.Serializable;
import java.util.*;
import fr.itris.glips.dbconn.util.HibernateUtil;
public interface DAO {
public void save(Object obj);
public void saveOrUpdate(Object obj);
public List<Object[]> listBySql(String sql);
public List listAll();
public List listAll(Class c);
public List list(String hql);
public List list( String hql, Object[] values);
public Class getEntiryClass();
public Object get( Serializable id);
public Object load( Serializable id);
public Object get(Class c, Serializable id);
public Object load(Class c,Serializable id);
}
实体类接口:
package fr.itris.glips.dbconn.module.dao;
public interface StationDAO extends DAO{
}
<!--[if !supportLists]-->2、 <!--[endif]-->实现类:
基类抽象实现类(所有实现类都继承该类):
package fr.itris.glips.dbconn.module.dao.impl;
import java.io.Serializable;
import java.util.List;
import fr.itris.glips.dbconn.module.dao.DAO;
import fr.itris.glips.dbconn.util.HibernateUtil;
public abstract class AbstractDAO implements DAO{
@Override
public void save(Object entity) {
// TODO Auto-generated method stub
HibernateUtil.save(entity);
}
@Override
public void saveOrUpdate(Object entity) {
// TODO Auto-generated method stub
HibernateUtil.saveOrUpdate(entity);
}
@Override
public List listBySql(String sql) {
// TODO Auto-generated method stub
return HibernateUtil.listBySql(sql);
}
@Override
public java.util.List listAll() {
// TODO Auto-generated method stub
return listAll(getEntiryClass());
}
public java.util.List listAll(Class c) {
// TODO Auto-generated method stub
return HibernateUtil.listAll(c);
}
@Override
public List list(String hql) {
// TODO Auto-generated method stub
return HibernateUtil.list(hql);
};
@Override
public List list(String hql, Object[] values) {
// TODO Auto-generated method stub
return HibernateUtil.list(hql,values);
}
public Object get( Serializable id){
return get(getEntiryClass(), id);
}
public Object load( Serializable id){
return load(getEntiryClass(), id);
}
public Object get(Class c, Serializable id){
return HibernateUtil.get(c, id);
}
public Object load(Class c,Serializable id){
return HibernateUtil.load(c, id);
}
abstract public Class getEntiryClass();
}
基类实现类:
package fr.itris.glips.dbconn.module.dao.impl;
import java.io.Serializable;
import java.util.List;
import fr.itris.glips.dbconn.module.dao.DAO;
import fr.itris.glips.dbconn.util.*;
public class BaseDAO extends AbstractDAO{
@Override
public Class getEntiryClass() {
// TODO Auto-generated method stub
return null;
}
}
实体类实现类:
package fr.itris.glips.dbconn.module.dao.impl;
import fr.itris.glips.dbconn.module.bean.SVGConfigure;
import fr.itris.glips.dbconn.module.bean.SVGElement;
import fr.itris.glips.dbconn.module.bean.Station;
import fr.itris.glips.dbconn.module.dao.SVGConfigureDAO;
import fr.itris.glips.dbconn.module.dao.SVGElementDAO;
import fr.itris.glips.dbconn.module.dao.StationDAO;
public class StationDAOImpl extends AbstractDAO implements StationDAO{
public Class getEntiryClass(){return Station.class;};
}
三、创建工厂管理 DAO 数据库操作类
1 创建 dao.xml , key 代表接口, value 代表实现类
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<section name="DAO">
<entry key="fr.itris.glips.dbconn.module.dao.DAO" value="fr.itris.glips.dbconn.module.dao.impl.BaseDAO"/>
<entry key="fr.itris.glips.dbconn.module.dao.SVGElementDAO" value="fr.itris.glips.dbconn.module.dao.impl.SVGElementDAOImpl"/>
<entry key="fr.itris.glips.dbconn.module.dao.SVGConfigureDAO" value="fr.itris.glips.dbconn.module.dao.impl.SVGConfigureDAOImpl"/>
<entry key="fr.itris.glips.dbconn.module.dao.StationDAO" value="fr.itris.glips.dbconn.module.dao.impl.StationDAOImpl"/>
<entry key="fr.itris.glips.dbconn.module.dao.SVGElementTypeDAO" value="fr.itris.glips.dbconn.module.dao.impl.SVGElementTypeDAOImpl"/>
</section>
</configuration>
<!--[if !supportLists]-->2、 <!--[endif]-->创建 ResourcesManager (管理资源文件的类)
package fr.itris.glips.dbconn.resources;
import fr.itris.glips.library.*;
import fr.itris.glips.svgeditor.*;
import org.apache.batik.dom.svg.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.net.*;
import java.awt.*;
import java.util.prefs.*;
/**
* @author ITRIS, Jordi SUC
*
* The class managing the resources
*/
public class ResourcesManager {
/**
* the map associating the name of a xml document to this document
*/
private final static HashMap<String, Document> cachedXMLDocuments=
new HashMap<String, Document>();
/**
* create a document from tthe given file in the resource files
* @param name the name of the xml file
* @return the document
*/
public static Document getXMLDocument(String name){
Document doc=null;
if(name!=null && ! name.equals("")){
if(cachedXMLDocuments.containsKey(name)){
doc=cachedXMLDocuments.get(name);
}else{
DocumentBuilderFactory docBuildFactory=
DocumentBuilderFactory.newInstance();
String path="";
try{
//parses the XML file
DocumentBuilder docBuild=docBuildFactory.newDocumentBuilder();
path=getPath("xml/"+name);
doc=docBuild.parse(path);
}catch (Exception ex){ex.printStackTrace();}
if(doc!=null){
cachedXMLDocuments.put(name, doc);
}
}
}
return doc;
}
public static String getPath(String resource){
String path="";
//System.out.println("resource="+resource);
try{
path=ResourcesManager.class.getResource(resource).toExternalForm();
}catch (Exception ex){
ex.printStackTrace();
path="";
}
//System.out.println("path="+path);
return path;
}
}
<!--[if !supportLists]-->3、 <!--[endif]-->创建 DAOConfig 类(解析 dao.xml 文件的类)
package fr.itris.glips.dbconn.resources;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import fr.itris.glips.dbconn.util.*;
import fr.itris.glips.svgeditor.NodeIterator;
public class DAOConfig {
private static final String DAO_CONFIG_FILE="dao.xml";
private static final String DAO_CONFIG_SECTION="DAO";
public static synchronized HashMap load(){
Document doc=ResourcesManager.getXMLDocument(DAO_CONFIG_FILE);
Element root=doc.getDocumentElement();
HashMap<Class,Class> map=new HashMap<Class,Class> ();
if(root!=null){
Node current=null;
for(current=root.getFirstChild(); current!=null; current=current.getNextSibling()){
String attr_name;
if(current!=null && current instanceof Element){
//System.out.println(current.getNodeName());
if(current.getNodeName()!=null &¤t.getNodeName().equals("section")){
attr_name=((Element)current).getAttribute("name");
Node current2;
if(attr_name!=null && attr_name.equals(DAO_CONFIG_SECTION)){
for(NodeIterator it2=new NodeIterator(current); it2.hasNext();){
current2=it2.next();
if(current2!=null && current2 instanceof Element){
if(current2.getNodeName()!=null&¤t2.getNodeName().equals("entry")){
String daoIface=((Element)current2).getAttribute("key");
//System.out.println("daoIface=="+daoIface);
String daoImpl=((Element)current2).getAttribute("value");
try{
Class iface=ClassToolKit.loadClass(daoIface);
Class impl=ClassToolKit.loadClass(daoImpl);
map.put(iface, impl);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
}
}
}
}
}
}
return map;
}
public static void main(String[] args){
load();
}
}
<!--[if !supportLists]-->4、 <!--[endif]-->创建 DAO 工厂类
package fr.itris.glips.dbconn.factory;
import java.util.*;
import fr.itris.glips.dbconn.exception.DataAccessException;
import fr.itris.glips.dbconn.module.dao.*;
import fr.itris.glips.dbconn.module.dao.impl.BaseDAO;
import fr.itris.glips.dbconn.resources.DAOConfig;
public class DaoFactory {
private static HashMap<Class,Class> daoClassMap =null;
static Map<String,DAO> daoMap=new HashMap<String,DAO>();
static {
initial();
}
public static synchronized void initial(){
if(null==daoClassMap){
daoClassMap=DAOConfig.load();
}
System.out.println("daoMap.size="+daoClassMap.size());
}
/**
* 获取 DAO 数据库操作类
* @param daoInterface DAO 接口
* @return 实现类
*/
public static DAO getDAO(Class daoInterface){
DAO dao=daoMap.get(daoInterface.getName());
if(dao==null){
try {
Class daoCl=getDAOClass(daoInterface);
dao=(DAO) daoCl.newInstance();
daoMap.put(daoInterface.getName(), dao);
} catch ( Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
return dao;
}
public static Class getDAOClass(Class daoInterface) {
Class dao=daoClassMap.get(daoInterface);
if(null==dao){
System.out.println("No Implementation found of DAO interface=?"+daoInterface.getName());
}
return dao;
}
public static void main(String[] args){
System.out.println("getClass="+DaoFactory.getDAO( DAO.class));
String sql="select name,aliasname from svgconfigure";
DAO dao=new BaseDAO();
List list=dao.listBySql(sql);
for(Object arr:list){
//System.out.println(arr[0]+","+arr[1]);
}
}
}
四、辅助类
1 、工具类
HibernateUtil 类( Hibernate 数据库操作类用到得工具类)
package fr.itris.glips.dbconn.util;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.beanutils.BeanUtils;
import org.hibernate.*;
import org.hibernate.cfg.*;
import fr.itris.glips.dbconn.page.PageInfo;
public class HibernateUtil {
private static ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
private static SessionFactory sessionFactory=null;
static {
initial();
}
public static void initial(){
if(sessionFactory==null){
try{
sessionFactory=new Configuration().configure().buildSessionFactory();
/*Configuration cfg=new Configuration()
.addClass(events.Event.class)
.setProperty("hibernate.dialect","org.hibernate.dialect.MySQLInnoDBDialect")
.setProperty("hibernate.connection.datasource","java:com/env/jdbc/sample")
.setProperty("hibernate.order_update","true");
sessionFactory=cfg.buildSessionFactory();*/
}catch(Throwable ex)
{
ex.printStackTrace();
}
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
public static Session getSession(){
//String f="sd/df";
return sessionFactory.openSession();
}
public static Session getCurrentSession(){
Session s=threadLocal.get();
if(s==null ){
s=sessionFactory.openSession();
threadLocal.set(s);
}
return s;
}
public static void closeCurrentSession(){
Session s=threadLocal.get();
if(s!=null){
s.close();
//s=null;
threadLocal.set(null);
}
}
//----------- 保存 --------
/**
* save 后数据进入一级缓存,不会进入二级缓存
* @param entity
*/
public static synchronized void save(Object entity){
Session session=getCurrentSession();
//Transaction tran=session.beginTransaction();
session.save(entity);
//tran.commit();
}
public static synchronized void saveOrUpdate(Object entity){
Session session=getCurrentSession();
//Transaction tran=session.beginTransaction();
session.saveOrUpdate (entity);
// tran.commit();
}
public void saveOrUpdateAll(final Collection entities){
Session session=getCurrentSession();
for (Iterator it = entities.iterator(); it.hasNext();) {
session.saveOrUpdate(it.next());
}
}
public void persist( final Object entity) {
Session session=getCurrentSession();
session.persist( entity);
}
public Object merge(final Object entity) {
Session session=getCurrentSession();
return session.merge( entity);
}
//---------------- 修改 --------
public void update(final Object entity ) {
Session session=getCurrentSession();
session.update(entity);
}
/**
*
* @param hql 也可用于删除,如: sql="delete TUser"
* @return
*/
public static int executeUpdate(String hql){
Session session=getCurrentSession();
//Transaction tran=session.beginTransaction();
Query query=session.createQuery(hql);
int n= query.executeUpdate();
//tran.commit();
return n;
}
public static void delete(Object obj){
Session session=getCurrentSession();
//Transaction tran=session.beginTransaction();
session.delete(obj);
//tran.commit();
}
/**
* @param sql 例如: sql="from TUser"
*/
public static void delete(String hql){
Session session=getCurrentSession();
//Transaction tran=session.beginTransaction();
session.delete(hql);
//tran.commit();
}
public void deleteAll(final Collection entities){
Session session=getCurrentSession();
for (Iterator it = entities.iterator(); it.hasNext();) {
session.delete(it.next());
}
}
public static void deleteById(Class cl,Serializable id){
Object obj=load(cl,id);
delete(obj);
}
public static int deleteAsScroll(String hql){
Session session=getCurrentSession();
Query query=session.createQuery(hql);
ScrollableResults scRes=query.scroll();
int i=0;
//Transaction tran=session.beginTransaction();
while(scRes.next()){
session.delete(scRes.get(i++));
}
//tran.commit();
return i;
}
//------------- 查询
/**
* 内部缓存和二级缓存查找
* 可返回代理类实例
* @param cl
* @param serializable
* @return
*/
public static Object load(Class cl,Serializable serializable){
Session session=getCurrentSession();
return session.load(cl, serializable);
}
/**
* 内部缓存查找
* 返回实体类
* @param cl
* @param serializable
* @return
*/
public static Object get(Class cl,Serializable serializable){
Session session=getCurrentSession();
return session.get(cl, serializable);
}
/**
* 一次取出所有数据
* 如果 hibernate.cache.use_query_cache 为 FALSE (系统默认),则不会利用缓存
* 否则,如果满足( 1 、完全相同的 SQL 重复执行, 2 、两次查询期间,对应的表没有发生过改变),利用缓存, key 为 sql 语句
* @param sql
* @return
*/
public static List list(String hql){
Session session=getCurrentSession();
Query query=session.createQuery(hql);
// 设置二级缓存
query.setCacheable(true);
return query.list();
}
/**
* Execute an HQL query, binding one value to a "?" parameter in the query string.
* @param queryString
* @param values
* @return
*/
public static List list(final String queryString, final Object[] values){
Session session=getCurrentSession();
Query queryObject = session.createQuery(queryString);
if (values != null) {
for (int i = 0; i < values.length; i++) {
queryObject.setParameter(i, values[i]);
}
}
return queryObject.list();
}
/**
* 一次取出一条数据
* *iterate 可充分利用缓存( key 为主键 Id ),但是如果缓存中查询不到,会出现 N+1 次查询 **
*
* * 首先执行一条 Select SQL 以获得所有符合条件的数据 id( 先在缓存中查找,如果查找不到就到数据库中查找 ) ,
* 随即, iterate 方法首先在本地缓存中根据 id 查找对应的实体对象是否存在(类似 Session.load() 方法),
* 如果缓存已经存在对应的数据,则直接以此数据对象作为查询结果,
* 如果没找到,再执行相应的 Select 语句获得对应的库表记录
* */
public static Iterator iterate(String sql){
Session session=getCurrentSession();
Query query=session.createQuery(sql);
// 设置二级缓存
query.setCacheable(true);
return query.iterate();
}
public static List listAll(Class c){
Session session=getCurrentSession();
Criteria criteria=session.createCriteria(c);
// 设置二级缓存
criteria.setCacheable(true);
return criteria.list();
}
/**
* 基于游标的数据遍历
* @param sql
* @return
*/
public static ScrollableResults scroll(String hql){
Session session=getCurrentSession();
Query query=session.createQuery(hql);
return query.scroll();
}
/**
*
* @param sql
* @return
*/
public static List listBySql (String sql){
Session session=getCurrentSession();
SQLQuery query=session.createSQLQuery(sql );
// 设置二级缓存
//query.setCacheable(true);
return query.list();
}
public static PageInfo pageQuery(Class c,PageInfo page){
Session session=getCurrentSession();
Criteria criteria=session.createCriteria(c);
// 设置二级缓存
criteria.setCacheable(true);
// 总数
page.setTotalRows(criteria.list().size());
int startIndex=(page.getPageNo()-1)*page.getPageSize();
criteria.setFirstResult(startIndex);
criteria.setMaxResults(page.getPageSize());
page.setPageContent(criteria.list());
return page;
}
public static PageInfo pageQuery(String hql,PageInfo page){
Session session=getCurrentSession();
Query query=session.createQuery(hql);
// 设置二级缓存
query.setCacheable(true);
page.setTotalRows(query.list().size());
int startIndex=(page.getPageNo()-1)*page.getPageSize();
query.setFirstResult(startIndex);
query.setMaxResults(page.getPageSize());
page.setPageContent(query.list());
return page;
}
public static void main(String[] args){
System.out.println("session=="+HibernateUtil.getSession());
}
}
ClassToolKit 类(根据类名生成类的类):
package fr.itris.glips.dbconn.util;
public class ClassToolKit{
public static Class loadClass(String className)throws ClassNotFoundException{
Class cls=null;
try{
cls=Thread.currentThread().getContextClassLoader().loadClass(className);
}catch(Exception e){
e.printStackTrace();
}
if(cls==null){
cls=Class.forName(className);
}
return cls;
}
}
<!--[if !supportLists]-->3、 <!--[endif]-->异常类
package fr.itris.glips.dbconn.exception;
public class DAOException extends RuntimeException{
private Throwable throwable;
public DAOException(String errorMassage){
super(errorMassage);
}
public DAOException(Throwable throwable){
this.throwable=throwable;
}
public DAOException(String errorMassage,Throwable throwable){
super(errorMassage);
this.throwable=throwable;
}
@Override
public void printStackTrace() {
if(throwable!=null){
System.err.println("A dao error has occured:");
throwable.printStackTrace();
}
}
}
类图: