HibUtil.java
package com.snow.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibUtil {
static Configuration conf = null;
static SessionFactory factory = null;
static Session session = null;
static{
try {
conf = new Configuration().configure();
factory = conf.buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获得Session连接
* */
public static Session getSession(){
session = factory.openSession();
return session;
}
/**
* 关闭session连接
* */
public static void closeSession(){
if(session!=null)
session.close();
}
public static void main(String[] args) {
System.out.println(getSession() == null);
}
}
BaseDao.java
package com.snow.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import com.snow.util.HibUtil;
public class BaseDao {
protected Session session = null;
protected Transaction ts = null;
protected Criteria criteria;
/**
* session保存方法
* */
public boolean save(Object obj){
boolean check = false;
try {
session = HibUtil.getSession();//获得连接
ts = session.beginTransaction();//创建事务
session.save(obj);//保存对象
ts.commit();//提交事务
check = true;
} catch (Exception e) {
e.printStackTrace();
ts.rollback();//出现异常则回滚事务
}
return check;
}
/**
* session删除方法
* */
public boolean delete(Object obj){
boolean check = false;
try {
session = HibUtil.getSession();
ts = session.beginTransaction();
session.delete(obj);
ts.commit();
check = true;
} catch (Exception e) {
e.printStackTrace();
ts.rollback();
}
return check;
}
/**
* session修改方法
* */
public boolean update(Object obj){
boolean check = false;
try {
session = HibUtil.getSession();
ts = session.beginTransaction();
session.update(obj);
ts.commit();
check = true;
} catch (Exception e) {
e.printStackTrace();
ts.rollback();
}
return check;
}
/**
* session查询方法(抓取)查询所有
* @return Criteria
* */
public Criteria QueryByFetch(String...fetch){
try {
if(fetch!=null && fetch.length>0){
for (int i = 0; i < fetch.length; i++) {
criteria = criteria.setFetchMode(fetch[i], FetchMode.JOIN);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return criteria;
}
/**
* 根据单条件或者多条件查询
* 至少2个参数,第一个为属性名,第二个为属性值
* @return Criteria
* */
public Criteria QueryByProperties(Object...properties){
try {
if(properties!=null && properties.length>0){
for (int i = 0; i < properties.length; i=i+2) {
criteria = criteria.add(Restrictions.like((String)properties[i], properties[i+1]));
}
}
return criteria;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 查询所有
* */
public Criteria Query(Class c){
session = HibUtil.getSession();
criteria = session.createCriteria(c);
return criteria;
}
/**
* 将查询结果返回List
* @return List
* */
public List QueryList(){
try {
return criteria.list();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 查询单个数据
* @return Object
* */
public Object QueryUnique(){
try {
return criteria.uniqueResult();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 此类专门用于分页
* */
/*public Criteria QueryByPage(PageInfo pageInfo){
return criteria.setFirstResult((pageInfo.getPageIndex()-1)* pageInfo.getPageSize())
.setMaxResults(pageInfo.getPageSize());
}*/
/**
* 此类专门用于排序
* */
public Criteria QueryByOrder(Order o){
return criteria.addOrder(o);
}
}
DBUtil.java
package com.snow.manager.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class DBUtil {
private static Properties p = new Properties();
static {
InputStream is = null;
is = DBUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
try {
p.load(is);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static Connection getConn() {
Connection conn = null;
try {
Class.forName(p.getProperty("driver"));
conn = DriverManager.getConnection(p.getProperty("url"), p.getProperty("username"), p.getProperty("password"));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static PreparedStatement getPs(Connection conn, String sql) {
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return ps;
}
public static void close(Connection conn) {
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(PreparedStatement ps) {
if(ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs) {
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
BaseDao.java
package com.snow.manager.dao;
import java.util.List;
public interface BaseDao<Entity> {
void save(Entity entity) throws Exception;
void update(Entity entity) throws Exception;
void delete(int id) throws Exception;
Entity findById(int i) throws Exception;
List<Entity> findAll() throws Exception;
public List<Entity> queryListForParams(String sql,Object[] params ) throws Exception;
int getTotal() throws Exception;
}
BaseDaoImpl.java
package com.snow.manager.dao.impl;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.snow.manager.dao.BaseDao;
import com.snow.manager.util.DBUtil;
public class BaseDaoImpl<Entity> implements BaseDao<Entity> {
protected Class clazz;
public BaseDaoImpl() {
ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass();
clazz = (Class) pt.getActualTypeArguments()[0];
}
@Override
public void save(Entity entity) throws Exception {
Connection conn = DBUtil.getConn();
String sql = "insert into " + clazz.getSimpleName().toLowerCase() + " values(null ";
Field[] fs = clazz.getDeclaredFields();
for(int i=1; i<fs.length; i++) {
sql += " , ? ";
}
sql += " ) ";
PreparedStatement ps = DBUtil.getPs(conn, sql);
for(int i=1; i<fs.length; i++) {
String methodName = "get" + Character.toUpperCase(fs[i].getName().charAt(0)) + fs[i].getName().substring(1);
Method m = clazz.getMethod(methodName);
ps.setObject(i, m.invoke(entity));
}
ps.executeUpdate();
DBUtil.close(ps);
DBUtil.close(conn);
}
@Override
public void update(Entity entity) throws Exception {
// TODO Auto-generated method stub
Connection conn = DBUtil.getConn();
String sql = "update " + clazz.getSimpleName().toLowerCase() + " set ";
Field[] fs = clazz.getDeclaredFields();
for(int i=1; i<fs.length; i++) {
sql += fs[i].getName() + " =?, ";
}
sql = sql.substring(0, sql.length() -2) + " where id = ? ";
PreparedStatement ps = DBUtil.getPs(conn, sql);
for(int i=1; i<fs.length; i++) {
String methodName = "get" + Character.toUpperCase(fs[i].getName().charAt(0)) + fs[i].getName().substring(1);
Method m = clazz.getMethod(methodName);
ps.setObject(i, m.invoke(entity));
}
Method m = clazz.getMethod("getId");
ps.setObject(fs.length, m.invoke(entity));
ps.executeUpdate();
DBUtil.close(ps);
DBUtil.close(conn);
}
@Override
public void delete(int id) throws Exception {
// TODO Auto-generated method stub
Connection conn = DBUtil.getConn();
String sql = "delete from " + clazz.getSimpleName().toLowerCase() + " where id = ? ";
PreparedStatement ps = DBUtil.getPs(conn, sql);
ps.setObject(1, id);
ps.executeUpdate();
DBUtil.close(ps);
DBUtil.close(conn);
}
@Override
public Entity findById(int id) throws Exception {
// TODO Auto-generated method stub
Connection conn = DBUtil.getConn();
String sql = "select * from " + clazz.getSimpleName().toLowerCase() + " where id = ? ";
PreparedStatement ps = DBUtil.getPs(conn, sql);
ps.setObject(1, id);
ResultSet rs = ps.executeQuery();
Entity entity = (Entity) clazz.newInstance();
Field[] fs = clazz.getDeclaredFields();
if(rs.next()) {
for(int i=0; i<fs.length; i++) {
String methodName = "set" + Character.toUpperCase(fs[i].getName().charAt(0)) + fs[i].getName().substring(1);
Method m = clazz.getMethod(methodName, fs[i].getType());
//锟缴诧拷锟斤拷锟斤拷写i
m.invoke(entity, rs.getObject(fs[i].getName()));
}
}
DBUtil.close(rs);
DBUtil.close(ps);
DBUtil.close(conn);
return entity;
}
@Override
public List<Entity> findAll() throws Exception {
// TODO Auto-generated method stub
Connection conn = DBUtil.getConn();
String sql = "select * from " + clazz.getSimpleName().toLowerCase();
PreparedStatement ps = DBUtil.getPs(conn, sql);
ResultSet rs = ps.executeQuery();
List<Entity> list = new ArrayList<Entity>();
Field[] fs = clazz.getDeclaredFields();
while(rs.next()){
Entity entity = (Entity) clazz.newInstance();
for(int i=0; i<fs.length; i++) {
String methodName = "set" + Character.toUpperCase(fs[i].getName().charAt(0)) + fs[i].getName().substring(1);
Method m = clazz.getMethod(methodName, fs[i].getType());
//锟缴诧拷锟斤拷锟斤拷写i
m.invoke(entity, rs.getObject(fs[i].getName()));
}
list.add(entity);
}
DBUtil.close(rs);
DBUtil.close(ps);
DBUtil.close(conn);
return list;
}
/**
* 鏉′欢鏌ヨ鐨勫弽灏勫皝瑁呮柟娉?
* @param sql
* @param params
* @return
*/
public List<Entity> queryListForParams(String sql,Object[] params ) throws Exception{
Connection conn = DBUtil.getConn();
PreparedStatement ps = null;
ResultSet rs = null;
List list = new ArrayList();
try {
// 寤虹珛statement瀵硅薄(灏佽浜唖ql)
ps = conn.prepareStatement(sql); // select * from org where id = ? and name = ? [1 , z3]
if(params!=null){
for(int i=0;i<params.length;i++){
ps.setObject(i+1, params[i]);
}
}
Field[] fs = clazz.getDeclaredFields();
rs = ps.executeQuery();
while(rs.next()){
Object obj = clazz.getConstructor().newInstance();
for(int i = 0 ; i <fs.length;i++ ){
String methodName = "set" +fs[i].getName().substring(0, 1).toUpperCase()+fs[i].getName().substring(1);
Method m = clazz.getMethod(methodName, fs[i].getType());
Object value = rs.getObject(fs[i].getName());
m.invoke(obj, value);
}
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
DBUtil.close(rs);
DBUtil.close(ps);
DBUtil.close(conn);
}
return list;
}
@Override
public int getTotal() throws Exception {
Connection conn = DBUtil.getConn();
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "select count(*) from " + clazz.getSimpleName().toLowerCase();
ps = DBUtil.getPs(conn, sql);
rs = ps.executeQuery();
int total = 0;
if(rs.next()){
total = rs.getInt(1);
}
DBUtil.close(rs);
DBUtil.close(ps);
DBUtil.close(conn);
return total;
}
}
未完待续...