Getting started with Hibernate----query,criteria,sqlquery

Source: Internet
Author: User

Hibernate's Query
HQL (Hibernate query Language) is a hibernate-specific query statement that transforms SQL statements into an object's operational format based on an object-oriented pattern.
List () query multiple lines

@Test        public void query(){            // sql : select 列名    from 表明;            // hql : select 属性名 from 类名;             //       select 别名.属性 from 类名 as 别名;            String hql = "from User";            Query query = session.createQuery(hql);            List list = query.list();            System.out.println(list);        }

When querying multiple properties, an array of objects is returned;
Where the first of the objects is the ID and the second element is PWD

String hql = "select id,pwd from user";    List<Object[]> list = session.createQuery(hql);

Uniqueresult () query a bar.

String hql = "select count(*) from User";          Query query = session.createQuery(hql);          Object uniqueResult = query.uniqueResult();

Paging Query
Setfirstresult (n): Nth data number of the query
Setmaxresults (20): Total amount of data queried

String hql = "from User";    Query query = session.createQuery(hql);    query.setFirstResult(1);    query.setMaxResults(20);    List list = query.list();    System.out.println(list);

Variable-parameter query (placeholder)

String hql = "from User where name = ? and age = ?";        Query query = session.createQuery(hql);        query.setParameter(0, "fy"); // query.setString(1, "fy");        query.setParameter(1, "18");        List list = query.list();        System.out.println(list);        常用写法:        String hql = "from User where name = :name and age = :age";        query.setString("name", "fy");        query.setString("age", "18");

Aggregation functions

count       返回的结果:Longmax/min     返回的结果:原始类型sum         返回的结果:Long或Doubleavg         返回的结果:Double

often use Uniqueresult () to get results because the returned result is usually a single data
Group queries

Query q = s.createQuery("select address,count(address) from UserModel group by address");

Sort queries

Query q = s.createQuery("from UserModel order by age desc");

Projection Data Encapsulation
Premise: The Usermodel (age,name) Construction method is required in the object model, and the parameter order must be consistent with the projection in HQL.

s.createQuery("select new UserModel(age,name) from UserModel");
——— the criteria of the ornate Division--–hibernate
The criteria query is also named QBC query, which completes the query operation in object-oriented format, and realizes the real automatic generation of SQL statements.
Query Single property: Returns the property type

Criteria criteria = session.createCriteria(User.class);      //Hibernate: select this_.name as y0_ from userdata this_      方式一:      Property pro = Property.forName("name");      criteria.setProjection(pro);      方式二:      PropertyProjection property = Projections.property("name");      criteria.setProjection(property);      List list = criteria.list();

Criteria.setprojection (property), cannot be duplicated, if repeated settings will overwrite the previous.
Querying multiple properties: Query result as an object array

1.声明查询属性的列表对象       ProjectionList li = Projections.projectionList();       2.声明要查询的属性       PropertyProjection name = Projections.property("name");       PropertyProjection id = Projections.property("id");       3.将查询的属性放入属性列表       li.add(id);       li.add(name);       4.为criteria设置属性列表       criteria.setProjection(li);       List<Object[]> list = criteria.list();

Aggregation functions

count:   行数            Projection condition = Projections.rowCount();          max/min: 最大值                Projection conditionMax = Projections.max("age");                   Projection conditionMin = Projections.min("age");               Sum  :   和            Projection conditionSum = Projections.sum("age");               Avg :    平均数            Projection conditionAvg = Projections.avg("age");

Group queries

Projections.groupProperty("address");

Sort

criteria.addOrder(Order.desc("age"));     criteria.addOrder(Order.asc("age"));

Conditional query.
Conditional query Use

Restrictions.eq 等于= Restrictions.allEq  使用Map,使用key/value进行多个等于的判断   Restrictions.gt 大于>   Restrictions.ge 大于等于>=   Restrictions.lt 小于<   Restrictions.le 小于等于<=   Restrictions.between    对应sql的between子句   Restrictions.like   对应sql的like子句   Restrictions.in 对应sql的in子句   Restrictions.and    and 关系   Restrictions.or or关系   Restrictions.sqlRestriction Sql限定查询   Criterion c = Restrictions.allEq(arg0);   criteria.add(c);

Offline query (Detachedcriteria)
Encapsulates the query field in the view layer into the Detachedcriteria object,
Detachedcriteria can be created without relying on the session. This way the session will not be exposed to the view and the business layer. Finally, in the controller layer, the Detachedcriteria is loaded into the criteria that can execute the query through the session.

表现层:    DetachedCriteria dc = DetachedCriteria.forClass(UserModel.class);    dc.add(Restrictions.like("address", "%"+address+"%"));    dc.add(Restrictions.between("age", age1, age2));    数据层:    Criteria c = dc.getExecutableCriteria(session);    c.list();

——— Gorgeous split--–hibernate sqlquery query
Executes the native SQL statement directly.

String sql = "select * from tbl_user";    SQLQuery sq = session.createSQLQuery(sql);    sq.list(); //uniqueResult()

Encapsulates the model data for a query by an alias.

String sql = "select u.* from tbl_user u";   SQLQuery sq = session.createSQLQuery(sql);   sq.addEntity("别名",模型类.class); // sq.addEntity("u",模型类.class);

——— Gorgeous split--– configuration type SQL/HQL statement
1. Configuring in the hibernate-mapping element of the Hbm.xml

When you configure SQL statements, you typically use XML syntax to avoid symbols in statements that conflict with XML syntax formatting. ' from user where age > : age : Age is also placeholder ' 1. Use query to execute queries ' query q = s.getnamedquery ("Query name in Configuration"); '

Getting started with Hibernate----query,criteria,sqlquery

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.