1.设置环境(以EClipse和hibernate 3.2.6为例)
1)首先,新建一个java 工程。
2) 将hiberante src导入到java的src目录下,此时多半会报错,不用管它!
3)将hiberante中lib的jar全部加入到buildpath上,并且把hibernate.jar加入到buildpath。
4)出错的话 自己检查一下 ,屏蔽掉部分出错代码即可,不影响跟踪。
5)在src目录下建立hibernate.cfg.xml(或者其它也可以)。
6)新建source Folder 目录 srcTest。
在其中建立类和映射文件User.hbm.xml(略)
public class User implements java.io.Serializable {
private Integer id;
private String username;
private String password;
。。。。。。。。。。。。。。
}
7)建立测试类(三种方式跟踪源码)
public class PagingTest {
/**
* @param args
*/
public void testQuery(){
Configuration config = new Configuration();
config.configure();
// 如果hibernate.cfg.xml中没有配置的某些属性,你可以通过config.setProperty(propertyName, value);来配置.
//如config.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
SessionFactory factory = config.buildSessionFactory();
Session session = factory.openSession();
Transaction tran = session.beginTransaction();
Query q = session.createSQLQuery("select * from USER_TABLE");
List l = q.list();
tran.commit();
System.out.println(l);
}
public void testCriteria(){
Configuration config = new Configuration();
config.configure();
// 如果hibernate.cfg.xml中没有配置的某些属性,你可以通过config.setProperty(propertyName, value);来配置.
//如config.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
SessionFactory factory = config.buildSessionFactory();
Session session = factory.openSession();
Transaction tran = session.beginTransaction();
Criteria criteria = session.createCriteria(User.class);
List l = criteria.list();
tran.commit();
System.out.println(l);
}
public void testNativeSql(){
Configuration config = new Configuration();
config.configure();
// 如果hibernate.cfg.xml中没有配置的某些属性,你可以通过config.setProperty(propertyName, value);来配置.
//如config.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
SessionFactory factory = config.buildSessionFactory();
Session session = factory.openSession();
Transaction tran = session.beginTransaction();
SQLQuery query = session.createSQLQuery("select * from USER_TABLE");
List l = query.list();
tran.commit();
System.out.println(l);
}
public static void main(String[] args) {
PagingTest pt=new PagingTest();
//pt.testCriteria();//select this_.USER_ID as USER1_0_0_, this_.USER_NAME as USER2_0_0_, this_.PASSWORD as PASSWORD0_0_ from USER_TABLE this_
//pt.testQuery();//select * from USER_TABLE
pt.testNativeSql();
}
}
2. 图片如下所示
3. 总结
有需要源码的可以联系我
微信公众号: 架构师日常笔记 欢迎关注!