关键代码:
String sql = "select ..."; session.createSQLQuery(sql)
AppTest.java:
package com.shuoeasy.test; import java.util.Arrays; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Conjunction; import org.hibernate.criterion.Disjunction; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.hibernate.service.ServiceRegistry; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Unit test for simple App. */ public class AppTest { Session session; SessionFactory sf; @Before public void init() { Configuration conf = new Configuration().configure(); ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build(); sf = conf.buildSessionFactory((org.hibernate.service.ServiceRegistry) sr); session = sf.openSession(); session.beginTransaction(); System.out.println("init"); } @After public void destory() { session.getTransaction().commit(); session.close(); sf.close(); System.out.println("dectory"); } /** * 插入数据 */ @Test public void testInsert(){ String sql = "INSERT INTO user(username) VALUES(?)"; Query query = session.createSQLQuery(sql); query.setString(0,"王五"); int ret = query.executeUpdate(); System.out.println(ret); } /** * 查询数据 */ @Test public void testList(){ String sql = "SELECT * FROM user"; Query query = session.createSQLQuery(sql); List<Object []> data = query.list(); System.out.println(data.size()); for(Object[] obj : data){ System.out.println(Arrays.asList(obj)); } } }