[Hibernate] - Criteria Select
使用Hibernate的Criteria做查询。
参考文档:
http://docs.jboss.org/hibernate/orm/3.5/reference/zh-CN/html/querycriteria.html
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<UserCard> 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<UserCard> getCards() { return cards; } public void setCards(Set<UserCard> 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<User> 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<UserCardTemp> 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<GroupByTemp> 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(); } }