从Hibernate中获得Connection,进行Jdbc操作的注意事项:
一定要进行事务处理,或hibernate事务处理或手工进行事务处理
//===============================================================================
样例一:hibernate事务处理
//===============================================================================
public void creatNewTable(String name){
String sql = "CREATE TABLE " + name + " (oid bigint NOT NULL ,flow_inc_code bigint NULL)";
Session session = HibernateSessionFactory.getSession();
Transaction tx = null;
Connection conn = null;
Statement stmt = null;
try{
tx = session.beginTransaction();
conn=session.connection();
stmt=conn.createStatement();
stmt.execute(sql);
tx.commit(); //使用 Hibernate事务处理边界
}
catch (Exception he){
tx.rollback();
}
finally{
if (conn != null) {
try {
conn.close();
}
catch(SQLException sqlex){
System.err.println(this.getClass().getName() + ".mymethod - 不能关闭数据库连接: " + sqlex.toString());
}
}
if (stmt != null) {
try {
stmt.close();
}
catch(SQLException sqlex){
System.err.println(this.getClass().getName() + ".mymethod - 不能关闭数据库连接: " + sqlex.toString());
}
}
session.close();
}
}
//===============================================================================
样例二:手工进行事务处理
//===============================================================================
public String createFormPhyTable(PubTableDef pubTableDef,
HttpServletRequest request) {
// 获得创建表单物理表sql:
String createTablesql = this
.createFormPhyTableSql(pubTableDef, request);
System.out
.println("DictionaryBOImpl.createFormPhyTable() -->> 创建表单物理表 00000 "
+ " createTablesql == " + createTablesql);
//Session session = HibernateSessionFactory.getSession();
// Transaction tx = null;
Connection conn = null;
Statement stmt = null;
try {
//tx = session.beginTransaction();
//conn=session.connection();
// conn = new JdbcUtil().getConnection();
// conn = new JdbcUtil().getJdbcConnection();
conn = new JdbcUtil().getHbmConnection();
conn.setAutoCommit(false);
System.out
.println("DictionaryBOImpl.createFormPhyTable() -->> 创建表单物理表 11111 "
+ " conn == " + conn);
java.sql.Statement statement = conn.createStatement();
statement.executeUpdate(createTablesql);// 创建表单物理表
conn.commit(); //此处一定要手工进行事务处理
statement.close();
//tx.commit(); //使用 Hibernate事务处理边界
conn.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
// No matter what, close the session
// statement.close();
}
return createTablesql;
};
//---------------------- JdbcUtil类的getHbmConnection方法 ----------------------------
public Connection getHbmConnection() throws Exception {
conn = HibernateSessionFactory.getSession().connection();
return conn;
}