HQL与Criteria
HQL(Hibernate Query Language)-官方推荐面向对象的查询语言,与SQL不同,HQL中的对象名是区分大小写的(除了JAVA类和属性其他部分不区分大小写);HQL中查的是对象而不是表,并且支持多态;HQL主要通过Query来操作,Query的创建方式:
Query q = session.createQuery(hql);
from Person
from User user where user.name=:name
from User user where user.name=:name and user.birthday < :birthday
Criteria是一种比HQL更面向对象的查询方式;Criteria的创建方式:
Criteria crit = session.createCriteria(DomainClass.class);
//简单属性条件如:
criteria.add(Restrictions.eq(propertyName, value)),
criteria.add(Restrictions.eqProperty(propertyName,otherPropertyName))
uniqueResult方法:当session.createQuery(“from xxx where cardid=’xxx'”).uniqueResult();返回的结果只有一个对象时,可以使用uniqueResult()得到该对象。但是,如果结果是多条,使用该方法就会抛出异常。
对象状态
- 瞬时(transient):数据库中没有数据与之对应,超过作用域会被JVM垃圾回收器回收,一般是new出来且与session没有关联的对象。
- 持久(persistent):数据库中有数据与之对应,当前与session有关联,并且相关联的session没有关闭,事务没有提交;持久对象状态发生改变,在事务提交时会影响到数据库(hibernate能检测到)。
- 脱管/游离(detached):数据库中有数据与之对应,但当前没有session与之关联;脱管对象状态发生改变,hibernate不能检测到。
对象关系映射
多对一(Employee – Department)
<many-to-one name=”depart” column=”depart_id”/>
一对多(Department-Employee)
<set name=”集合对象属性名”>=”外键名”/> =”集合放入的类名”/> >
一对一(Person – IdCard)
<id name=”id”>=”foreign”>name=”property”>person > <one-to-one name=” person” constrained=”true”/>
Original: https://www.cnblogs.com/xrwdgj/p/16299019.html
Author: 小人物大格局
Title: Hibernate基础入门2
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/592854/
转载文章受原作者版权保护。转载请注明原作者出处!