BaseDao
package dao;
import java.sql.*;
public class BaseDao {
public Connection getCon(){
Connection con = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "system", "orcl");
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
public void closeAll(Connection con,Statement stmt,ResultSet rs){
if(rs != null){
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
if(con != null && !con.isClosed()){
con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
===========================================================================================
package dao;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
@Entity
public class BaseDao {
/**
* 查找
*/
public List find(String hql,Object[] args){
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Query query = session.createQuery(hql);
for (int i = 0; i < args.length; i++) {
// query.setEntity( i + 1, args[i]);
query.setParameter(i, args[i]);
}
List list = query.list();
session.close();
return list;
}
public List find(String hql){
return this.find(hql, new Object[]{});
}
public Object getById(String hql, Serializable id){
List find = this.find(hql, new Object[]{id});
if(find.size() > 0 ){
return find.get(0);
}
return null;
}
public Object getObject(String hql){
List find = this.find(hql, new Object[]{});
return null;
}
/**
* 添加
* @param objdct
*/
public void add(Object objdct){
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.save(objdct);
tx.commit();
session.close();
}
/**
* 修改
* @param objdct
*/
public void edit(Object object){
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.update(object);
tx.commit();
session.close();
}
/**
* 修改
* @param objdct
*/
public void edit( String hql,Object[] args){
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery(hql);
for (int i = 0; i < args.length; i++) {
query.setParameter(i, args[i]);
}
query.executeUpdate();
tx.commit();
session.close();
}
}