《Hibernate 系列》- Hql语法

2018-01-11 13:00:19来源:oschina作者:Kimisme人点击

分享
跟我学

项目结构



--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/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">










hibernate.cfg.xml



"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">


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/c_hql/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();

Query query = session.createQuery("from com.easy.c_hql.User");
Listlist=query.list();
System.out.println(list);

session.close();
}

查询单行数据


public void test_query_single_row(){
Session session = HibernateUtils.openSession();

Query query = session.createQuery("from com.easy.c_hql.User u where u.id=1");
User user =(User)query.uniqueResult();
System.out.println(user);

session.close();
}

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台