跟我学
项目结构
--src/main/java----com.easy.c_hql------HibernateUtils.java------TestApp.java------User.java------hibernate.cfg.xml------User.hbm.xml
User.java
public class User { private Integer id; private String username; private Integer age;
User.hbm.xml
hibernate.cfg.xml
com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/test root 123456 true true update
HibernateUtils.java
public class HibernateUtils { private static SessionFactory sessionFactory; static{ URL url=HibernateUtils.class.getClass().getResource("/com/easy/d_criteria/hibernate.cfg.xml"); Configuration conf=new Configuration().configure(url); sessionFactory =conf.buildSessionFactory(); Runtime.getRuntime().addShutdownHook(new Thread( new Runnable() { @Override public void run() { System.out.println("虚拟机关闭,释放资源"); sessionFactory.close(); } })); } public static Session openSession(){ return sessionFactory.openSession(); } public static Session getCurrentSession(){ return sessionFactory.getCurrentSession(); }}
UT
查询多行数据
public void test_query_multi_rows(){ Session session = HibernateUtils.openSession(); Criteria criteria =session.createCriteria(User.class); criteria.add(Restrictions.like("username", "%rose%")); Listlist=criteria.list(); System.out.println(list); session.close(); }
查询单行数据
public void test_query_single_row(){ Session session = HibernateUtils.openSession(); Criteria criteria =session.createCriteria(User.class); criteria.add(Restrictions.eq("id", 1)); User user =(User)criteria.uniqueResult(); System.out.println(user); session.close(); }