(七)Hibernate中使用JDBC
时间:2021-07-01 10:21:17
帮助过:17人阅读
action;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cache.spi.QueryResultsRegion;
import org.hibernate.jdbc.ReturningWork;
import bean.User;
import util.HibernateUtil;
public class Query_JDBC {
public static void main(String[] args) {
Query_JDBC.jdbc();
}
/**
* 在Hibernate中获取Connection接口
*/
private static void jdbc() {
Session session =
null;
Transaction tran =
null;
try {
session =
HibernateUtil.getSession();
tran =
session.beginTransaction();
User user = session.doReturningWork(
new ReturningWork<User>
() {
@Override
public User execute(Connection conn)
throws SQLException {
QueryRunner queryRunner =
new QueryRunner();
String sql = "select username,userid,is_admin as isadmin from user where userid=1";
//数据库中的is_admin和bean中的isdmin不一致
User user =
queryRunner.query(conn, sql,
new BeanHandler<User>(User.
class));
return user;
}
});
System.out.println("username=" + user.getUsername() + "\t"
+ "userid=" + user.getUserid() + "\t" + "isadmin?"
+
user.getIsAdmin());
tran.commit();
} catch (Exception e) {
e.printStackTrace();
tran.rollback();
} finally {
HibernateUtil.closeSession();
}
}
}
结果:
代码在下面章节
(七)Hibernate中使用JDBC
标签:技术 color ace import 使用 turn lex dbutil 数据库