Spingboot?JPA?CriteriaBuilder?如何獲取指定字段
更新時間:2021年12月07日 08:53:39 作者:sunlight
這篇文章?主要介紹了Spingboot?JPA?CriteriaBuilder?如何獲取指定字段,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
Spingboot JPA CriteriaBuilder獲取指定字段
廢話不說直接貼代碼
public class ActivityVO implements Serializable { private static final long serialVersionUID = 1L; private int id; private String name; private String thumb; public ActivityVO(int id, String name, String thumb) { this.id = id; this.name = name; this.thumb = thumb; } public ActivityVO(){ } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getThumb() { return thumb; } public void setThumb(String thumb) { this.thumb = thumb; } }
import org.hibernate.annotations.NotFound; import org.hibernate.annotations.NotFoundAction; import java.io.Serializable; import javax.persistence.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import java.util.Map; import java.util.Objects; /** * The persistent class for the activity database table. * */ @Entity @Table(name="activity") //@JsonIgnoreProperties({"user"}) //@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) //@NamedQuery(name = "Task.findByTaskName", query = "select t from Task t where t.taskName = ?1") public class ActivityEntity implements Serializable { private static final long serialVersionUID = 1L; public ActivityEntity(int id, String name, String thumb) { this.id = id; this.name = name; } private int id; private Integer userId; private String name; private String thumb; private byte type; private byte mode; private String notes; private String content; private BigDecimal deposit; private byte status; private int productNum; private Integer participantNum; private Integer wxId; private Integer mpId; private String mpRelpyKeyword; private BigInteger startTime; private byte lotteryType; private BigInteger lotteryTime; private int maxParticipantNum; private byte enableBlacklist; private byte enableSharing; private byte isVisible; private BigInteger createTime; private BigInteger updateTime; public ActivityEntity() { } @Id @Column(name = "id") @GeneratedValue(strategy=GenerationType.IDENTITY) public int getId() { return id; } public void setId(int id) { this.id = id; } @Basic @Column(name = "user_id") public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } @Basic @Column(name = "name") public String getName() { return name; } public void setName(String name) { this.name = name; } @Basic @Column(name = "thumb") public String getThumb() { return thumb; } public void setThumb(String thumb) { this.thumb = thumb; } @Basic @Column(name = "type") public byte getType() { return type; } public void setType(byte type) { this.type = type; } @Basic @Column(name = "mode") public byte getMode() { return mode; } public void setMode(byte mode) { this.mode = mode; } @Basic @Column(name = "notes") public String getNotes() { return notes; } public void setNotes(String notes) { this.notes = notes; } @Basic @Column(name = "content") public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Basic @Column(name = "deposit") public BigDecimal getDeposit() { return deposit; } public void setDeposit(BigDecimal deposit) { this.deposit = deposit; } @Basic @Column(name = "status") public byte getStatus() { return status; } public void setStatus(byte status) { this.status = status; } @Basic @Column(name = "product_num") public int getProductNum() { return productNum; } public void setProductNum(int productNum) { this.productNum = productNum; } @Basic @Column(name = "participant_num") public Integer getParticipantNum() { return participantNum; } public void setParticipantNum(Integer participantNum) { this.participantNum = participantNum; } @Basic @Column(name = "wx_id") public Integer getWxId() { return wxId; } public void setWxId(Integer wxId) { this.wxId = wxId; } @Basic @Column(name = "mp_id") public Integer getMpId() { return mpId; } public void setMpId(Integer mpId) { this.mpId = mpId; } @Basic @Column(name = "mp_relpy_keyword") public String getMpRelpyKeyword() { return mpRelpyKeyword; } public void setMpRelpyKeyword(String mpRelpyKeyword) { this.mpRelpyKeyword = mpRelpyKeyword; } @Basic @Column(name = "start_time") public BigInteger getStartTime() { return startTime; } public void setStartTime(BigInteger startTime) { this.startTime = startTime; } @Basic @Column(name = "lottery_type") public byte getLotteryType() { return lotteryType; } public void setLotteryType(byte lotteryType) { this.lotteryType = lotteryType; } @Basic @Column(name = "lottery_time") public BigInteger getLotteryTime() { return lotteryTime; } public void setLotteryTime(BigInteger lotteryTime) { this.lotteryTime = lotteryTime; } @Basic @Column(name = "max_participant_num") public int getMaxParticipantNum() { return maxParticipantNum; } public void setMaxParticipantNum(int maxParticipantNum) { this.maxParticipantNum = maxParticipantNum; } @Basic @Column(name = "enable_blacklist") public byte getEnableBlacklist() { return enableBlacklist; } public void setEnableBlacklist(byte enableBlacklist) { this.enableBlacklist = enableBlacklist; } @Basic @Column(name = "enable_sharing") public byte getEnableSharing() { return enableSharing; } public void setEnableSharing(byte enableSharing) { this.enableSharing = enableSharing; } @Basic @Column(name = "is_visible") public byte getIsVisible() { return isVisible; } public void setIsVisible(byte isVisible) { this.isVisible = isVisible; } @Basic @Column(name = "create_time") public BigInteger getCreateTime() { return createTime; } public void setCreateTime(BigInteger createTime) { this.createTime = createTime; } @Basic @Column(name = "update_time") public BigInteger getUpdateTime() { return updateTime; } public void setUpdateTime(BigInteger updateTime) { this.updateTime = updateTime; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ActivityEntity that = (ActivityEntity) o; return id == that.id && type == that.type && mode == that.mode && status == that.status && productNum == that.productNum && lotteryType == that.lotteryType && maxParticipantNum == that.maxParticipantNum && enableBlacklist == that.enableBlacklist && Objects.equals(userId, that.userId) && Objects.equals(name, that.name) && Objects.equals(thumb, that.thumb) && Objects.equals(notes, that.notes) && Objects.equals(content, that.content) && Objects.equals(deposit, that.deposit) && Objects.equals(participantNum, that.participantNum) && Objects.equals(wxId, that.wxId) && Objects.equals(mpId, that.mpId) && Objects.equals(mpRelpyKeyword, that.mpRelpyKeyword) && Objects.equals(startTime, that.startTime) && Objects.equals(lotteryTime, that.lotteryTime) && Objects.equals(createTime, that.createTime) && Objects.equals(updateTime, that.updateTime) && Objects.equals(user, that.user); } @Override public int hashCode() { return Objects.hash(id, userId, name, thumb, type, mode, notes, content, deposit, status, productNum, participantNum, wxId, mpId, mpRelpyKeyword, startTime, lotteryType, lotteryTime, maxParticipantNum, enableBlacklist, createTime, updateTime, user); } @Override public String toString() { return "ActivityEntity{" + "id=" + id + ", userId=" + userId + ", name='" + name + '\'' + ", thumb='" + thumb + '\'' + ", type=" + type + ", mode=" + mode + ", notes='" + notes + '\'' + ", content='" + content + '\'' + ", deposit=" + deposit + ", status=" + status + ", productNum=" + productNum + ", participantNum=" + participantNum + ", wxId=" + wxId + ", mpId=" + mpId + ", mpRelpyKeyword='" + mpRelpyKeyword + '\'' + ", startTime=" + startTime + ", lotteryType=" + lotteryType + ", lotteryTime=" + lotteryTime + ", maxParticipantNum=" + maxParticipantNum + ", enableBlacklist=" + enableBlacklist + ", createTime=" + createTime + ", updateTime=" + updateTime + ", user=" + user + '}'; } }
@PersistenceContext//@Autowired和@PersistenceContext注解任取一 EntityManager entityManager; public List<ActivityVO> findAllByPage(Pageable pageable) throws Exception { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Tuple> criteriaQuery = criteriaBuilder.createTupleQuery(); Root<ActivityEntity> root = criteriaQuery.from(ActivityEntity.class); criteriaQuery.multiselect( root.get("id"), root.get("name"),root.get("thumb") ); Predicate restrictions = criteriaBuilder.conjunction(); restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("id"), 1)); criteriaQuery.where(restrictions); criteriaQuery.orderBy(criteriaBuilder.desc(root.get("id"))); TypedQuery<Tuple> query = entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT); List<Tuple> tuples = query.getResultList(); ActivityVO adminWrapper = null; List<ActivityVO> lists = new ArrayList<ActivityVO>(); for (Tuple t : tuples) { adminWrapper = new ActivityVO(); adminWrapper.setId((Integer) t.get(0)); adminWrapper.setName((String)t.get(1)); adminWrapper.setThumb((String)t.get(2)); lists.add(adminWrapper); } return lists; } }
Java JPA CriteriaBuilder使用
一個復雜的查詢例子
包含常用的所有查詢方法
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); //查詢結(jié)果所需要的類型(Entity相對應(yīng)) CriteriaQuery<Entity> criteriaQuery = criteriaBuilder.createQuery(Entity.class); //查詢所需要的主體類(Entity0相對應(yīng)) Root<Entity0> root = criteriaQuery.from(Entity0.class); //查詢結(jié)果-select(此處查詢所有符合條件的主體類) criteriaQuery.select(root); //過濾條件用Predicate方法拼接 Predicate restrictions = criteriaBuilder.conjunction(); //過濾條件——equal(當Entity0關(guān)聯(lián)member類時,Entity0:member=m:1) restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member)); //過濾條件——like restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.like(root.<String>get("str"), "%"+str+"%")); //用戶名查詢(member里面的username匹配) ———— 多層查詢 ———— 子查詢的一種:適用于m:1或1:1(即多對一或一對一) restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.like(root.get("member").<String>get("username"), "%"+username+"%")); //子查詢(規(guī)范寫法,先判斷查詢內(nèi)容是否存在)(適用于1:m)(即一對多) if (searchType != null || searchValue != null || hasExpired != null || status != null || type != null || isPendingReceive != null || isPendingRefunds != null || isAllocatedStock != null || businessType != null) { //建立子查詢 Subquery<Order> orderSubquery = criteriaQuery.subquery(Order.class); Root<Order> orderSubqueryRoot = orderSubquery.from(Order.class); orderSubquery.select(orderSubqueryRoot); //子查詢和父查詢相關(guān)聯(lián) Predicate orderRestrictions = criteriaBuilder.equal(orderSubqueryRoot.<MergeOrder>get("mergeOrder"), root); //子查詢過濾條件拼接 if (searchType != null && searchValue != null) {if ("phone".equals(searchType)) { orderRestrictions = criteriaBuilder.and(orderRestrictions, criteriaBuilder.like(orderSubqueryRoot.<String>get("phone"), "%"+searchValue+"%")); } }if (type != null) { CriteriaBuilder.In<Order.Type> in = criteriaBuilder.in(orderSubqueryRoot.<Order.Type>get("type")); in.value(type); orderRestrictions = criteriaBuilder.and(orderRestrictions, in); } //and、or以及判斷是否為null,比較(>)的使用(比較可以用于日期比較) if (hasExpired != null) { orderRestrictions = criteriaBuilder.and(orderRestrictions, criteriaBuilder.or(orderSubqueryRoot.get("expire").isNull(), criteriaBuilder.greaterThan(orderSubqueryRoot.<Date>get("expire"), new Date()))); } // not的使用方法(不符合上述過濾條件),notEqual的使用,<(小于)的使用 if (isPendingReceive != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("paymentMethodType"), PaymentMethod.Type.cashOnDelivery)); Predicate predicate = criteriaBuilder.and(criteriaBuilder.or(orderSubqueryRoot.get("expire").isNull() , criteriaBuilder.greaterThan(orderSubqueryRoot.<Date>get("expire"), new Date())) , criteriaBuilder.notEqual(orderSubqueryRoot.get("status"), Order.Status.completed) , criteriaBuilder.lessThan(orderSubqueryRoot.<BigDecimal>get("amountPaid"), orderSubqueryRoot.<BigDecimal>get("amount"))); if (isPendingReceive) { orderRestrictions = criteriaBuilder.and(orderRestrictions, criteriaBuilder.not(predicate)); } }// 多層查詢使用if (businessType != null) { orderRestrictions = criteriaBuilder.and(orderRestrictions, criteriaBuilder.equal(orderSubqueryRoot.get("store").get("business").get("businessType"), businessType)); } // 拼接過濾條件 orderSubquery.where(orderRestrictions); // 和總條件拼接(exists的使用) restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(orderSubquery)); } criteriaQuery.where(restrictions); TypedQuery<Entity> query = entityManager.createQuery(criteriaQuery); Entity singleResult = query.getSingleResult();
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java經(jīng)典面試題匯總:網(wǎng)絡(luò)編程
本篇總結(jié)的是Java 網(wǎng)絡(luò)編程相關(guān)的面試題,后續(xù)會持續(xù)更新,希望我的分享可以幫助到正在備戰(zhàn)面試的實習生或者已經(jīng)工作的同行,如果發(fā)現(xiàn)錯誤還望大家多多包涵,不吝賜教,謝謝2021-07-07基于java中byte數(shù)組與int類型的轉(zhuǎn)換(兩種方法)
下面小編就為大家?guī)硪黄趈ava中byte數(shù)組與int類型的轉(zhuǎn)換(兩種方法)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08Springboot項目中定時任務(wù)的四種實現(xiàn)方式詳解
Spring的@Scheduled注解是一種非常簡單和便捷的實現(xiàn)定時任務(wù)的方式,通過在方法上添加@Scheduled注解,我們可以指定方法在特定的時間間隔或固定的時間點執(zhí)行,本文給大家介紹Springboot項目中定時任務(wù)的四種實現(xiàn)方式,感興趣的的朋友一起看看b2024-02-02java web在高并發(fā)和分布式下實現(xiàn)訂單號生成唯一的解決方案
這篇文章主要介紹了java web在高并發(fā)和分布式下實現(xiàn)訂單號生成唯一的解決方案,需要的朋友可以參考下2017-11-11