博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Hibernate] - Criteria Select
阅读量:5895 次
发布时间:2019-06-19

本文共 13104 字,大约阅读时间需要 43 分钟。

使用Hibernate的Criteria做查询。

参考文档:

 


 

Java Beans:

package com.my.bean;import java.util.Date;import java.util.Set;import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.OneToMany;import javax.persistence.Table;@Entity@Table(name="user")public class User {    @Id @GeneratedValue @Column(name="user_id", nullable=false)    private long userID;        @Column(name="user_name", length=100, nullable=false)    private String userName;        @Column(name="create_time", nullable=false)    private Date createTime;        @OneToMany(mappedBy="user", cascade=CascadeType.ALL)    private Set
cards; public long getUserID() { return userID; } public void setUserID(long userID) { this.userID = userID; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Set
getCards() { return cards; } public void setCards(Set
cards) { this.cards = cards; }}
package com.my.bean;import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.ManyToOne;import javax.persistence.Table;@Entity@Table(name="user_card")public class UserCard {    @Id    @GeneratedValue(strategy=GenerationType.IDENTITY)    @Column(name="card_id")    private long cardID;        @Column(name="card_name")    private String cardName;        @ManyToOne(cascade=CascadeType.ALL)    @JoinColumn(name="user_id")    private User user;        public long getCardID() {        return cardID;    }    public void setCardID(long cardID) {        this.cardID = cardID;    }    public String getCardName() {        return cardName;    }    public void setCardName(String cardName) {        this.cardName = cardName;    }    public User getUser() {        return user;    }    public void setUser(User user) {        this.user = user;    }}

 

Java DTO beans:

package com.my.bean.dto;public class GroupByTemp {    private long sumUser;    private long count;    private long userID;        public long getSumUser() {        return sumUser;    }    public void setSumUser(long sumUser) {        this.sumUser = sumUser;    }    public long getCount() {        return count;    }    public void setCount(long count) {        this.count = count;    }    public long getUserID() {        return userID;    }    public void setUserID(long userID) {        this.userID = userID;    }}
package com.my.bean.dto;public class UserCardTemp {    private long userID;    private String userName;    private String cardName;    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }        public String getCardName() {        return cardName;    }    public void setCardName(String cardName) {        this.cardName = cardName;    }    public UserCardTemp() {    }    public long getUserID() {        return userID;    }    public void setUserID(long userID) {        this.userID = userID;    }    }

 

测试例子:

package com.my.init;import java.util.List;import org.hibernate.Criteria;import org.hibernate.Session;import org.hibernate.Transaction;import org.hibernate.criterion.DetachedCriteria;import org.hibernate.criterion.Order;import org.hibernate.criterion.ProjectionList;import org.hibernate.criterion.Projections;import org.hibernate.criterion.Property;import org.hibernate.criterion.Restrictions;import org.hibernate.sql.JoinType;import org.hibernate.transform.Transformers;import com.my.bean.User;import com.my.bean.UserCard;import com.my.bean.dto.GroupByTemp;import com.my.bean.dto.UserCardTemp;import com.my.dao.util.HibernateUtil;public class Test {    @SuppressWarnings("unchecked")    public static void main(String[] args) {        Session session = HibernateUtil.getSessionFactory().openSession();        Transaction tx = session.beginTransaction();        try {            // ----------------------------------------------------            // Set limit and get user info            // ----------------------------------------------------            Criteria crit = session.createCriteria(User.class);            List
users = crit.setFirstResult(1).setMaxResults(1).list(); for (User user : users) { System.out.println("User name:" + user.getUserName()); } // ---------------------------------------------------- // Order by // ---------------------------------------------------- crit = session.createCriteria(User.class); crit.addOrder(Order.desc("userName")); crit.addOrder(Order.asc("userID")); users = crit.list(); for (User user : users) { System.out.println("User name:" + user.getUserName()); } // ---------------------------------------------------- // Where: like and equal // ---------------------------------------------------- crit = session.createCriteria(User.class); crit.add(Restrictions.like("userName", "%b%")).add( Restrictions.eq("userID", (long) 1)); users = crit.list(); for (User user : users) { System.out.println("User name:" + user.getUserName()); } // ---------------------------------------------------- // Where: more than or less than // ---------------------------------------------------- crit = session.createCriteria(User.class); crit.add(Restrictions.or(Restrictions.gt("userID", (long) 1)).add( Restrictions.lt("userID", (long) 2))); users = crit.list(); for (User user : users) { System.out.println("User name:" + user.getUserName()); } // ---------------------------------------------------- // Where: in // ---------------------------------------------------- crit = session.createCriteria(User.class); crit.add(Restrictions.in("userName", new String[] { "Robin", "Amy" })); users = crit.list(); for (User user : users) { System.out.println("User name:" + user.getUserName()); } // ---------------------------------------------------- // Property // ---------------------------------------------------- crit = session.createCriteria(User.class); crit.add(Property.forName("userName").like("%b%")) .add(Property.forName("userID").between((long) 1, (long) 2)) .addOrder(Property.forName("userID").desc()); users = crit.list(); for (User user : users) { System.out.println("User name:" + user.getUserName()); } // ---------------------------------------------------- // Left join // ---------------------------------------------------- crit = session.createCriteria(User.class); crit.add(Restrictions.eq("userName", "Robin")).setFetchMode( "cards", org.hibernate.FetchMode.JOIN); users = crit.list(); for (User user : users) { System.out.println("User name:" + user.getUserName()); } // ---------------------------------------------------- // Left join 2 // ---------------------------------------------------- crit = session.createCriteria(User.class); crit.createAlias("cards", "C", JoinType.LEFT_OUTER_JOIN); crit.add(Restrictions.eq("userName", "Robin")); users = crit.list(); for (User user : users) { System.out.println("User name:" + user.getUserName()); } // ---------------------------------------------------- // Inner join // ---------------------------------------------------- crit = session.createCriteria(User.class); crit.add(Restrictions.eq("userName", "Robin")); crit.createCriteria("cards").add( Restrictions.eq("cardID", (long) 1)); users = crit.list(); for (User user : users) { System.out.println("User name:" + user.getUserName()); } // ---------------------------------------------------- // Inner join 2 // ---------------------------------------------------- crit = session.createCriteria(User.class); crit.add(Restrictions.eq("userName", "Robin")); crit.createAlias("cards", "C", JoinType.INNER_JOIN); users = crit.list(); for (User user : users) { System.out.println("User name:" + user.getUserName()); } // ---------------------------------------------------- // Count // ---------------------------------------------------- crit = session.createCriteria(User.class); crit.setProjection(Projections.rowCount()).add( Restrictions.eq("userName", "Robin")); System.out.println("Row count:" + crit.uniqueResult().toString()); // ---------------------------------------------------- // Max // ---------------------------------------------------- crit = session.createCriteria(User.class); crit.setProjection(Projections.max("userID")); System.out.println("Max ID:" + crit.uniqueResult().toString()); // ---------------------------------------------------- // Min // ---------------------------------------------------- crit = session.createCriteria(User.class); crit.setProjection(Projections.min("userID")); System.out.println("Max ID:" + crit.uniqueResult().toString()); // ---------------------------------------------------- // ProjectionList and left join // ---------------------------------------------------- crit = session.createCriteria(User.class); crit.createAlias("cards", "C", JoinType.LEFT_OUTER_JOIN); ProjectionList proList = Projections.projectionList(); proList.add(Projections.property("userID"), "userID"); proList.add(Projections.property("userName"), "userName"); proList.add(Projections.property("C.cardName"), "cardName"); crit.setProjection(proList); crit.setResultTransformer(Transformers .aliasToBean(UserCardTemp.class)); List
temps = crit.list(); for (UserCardTemp uc : temps) { System.out.println("User ID:" + uc.getUserID() + "\tUser name:" + uc.getUserName() + "\tCard name:" + uc.getCardName()); } // ---------------------------------------------------- // ProjectionList Group by // ---------------------------------------------------- crit = session.createCriteria(User.class); crit.createAlias("cards", "C", JoinType.LEFT_OUTER_JOIN); proList = Projections.projectionList(); proList.add(Projections.sum("userID"), "sumUser"); proList.add(Projections.count("userID"), "count"); proList.add(Projections.groupProperty("userID"), "userID"); crit.setProjection(proList); crit.setResultTransformer(Transformers .aliasToBean(GroupByTemp.class)); List
gt = crit.list(); for (GroupByTemp g : gt) { System.out.println("Sum:" + g.getSumUser() + "\tUser ID:" + g.getUserID() + "\tCount:" + g.getCount()); } // ---------------------------------------------------- // Sub search // ---------------------------------------------------- crit = session.createCriteria(User.class); DetachedCriteria sub = DetachedCriteria.forClass(UserCard.class); sub.setProjection(Property.forName("cardID")); sub.add(Restrictions.eq("cardID", (long) 1)); crit.add(Property.forName("cards").in(sub)); users = crit.list(); for (User item : users) { System.out.println("User ID:" + item.getUserID()); } tx.commit(); } catch (Exception e) { tx.rollback(); e.printStackTrace(); } session.close(); }}

 

转载地址:http://ujxsx.baihongyu.com/

你可能感兴趣的文章
[HNOI2009]最小圈
查看>>
采购订单保存不能修改供应商
查看>>
Jdom的简单操作
查看>>
网络设备
查看>>
HDU6446
查看>>
登陆界面针对不同分辨率的兼容性调整(媒体查询)
查看>>
7. 整数反转
查看>>
poj3109树状数组+扫描线
查看>>
OC协议
查看>>
mysql利用binlog恢复数据详细例子
查看>>
江西财经大学第一届程序设计竞赛 I 题 小P和小Q
查看>>
Android数据存储--数据库的操作
查看>>
软件工程(2018)第5次团队作业
查看>>
left join on/right join on/inner join on/full join on连接
查看>>
接口测试框架(一)
查看>>
CDI Event解析
查看>>
Wiggle SortII
查看>>
LeetCode 218: The Skyline Problem
查看>>
Codeforces 582B Once Again
查看>>
JVM加载class文件的原理机制
查看>>