日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

使用Hibernate的JPA 2.0标准查询

發(fā)布時(shí)間:2023/12/3 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用Hibernate的JPA 2.0标准查询 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
JPA 2.0中引入了條件查詢(xún) 。 借助條件查詢(xún),您可以以類(lèi)型安全的方式編寫(xiě)查詢(xún)。 在進(jìn)行標(biāo)準(zhǔn)查詢(xún)之前,開(kāi)發(fā)人員必須通過(guò)構(gòu)建基于對(duì)象的查詢(xún)定義來(lái)編寫(xiě)查詢(xún)。 構(gòu)建查詢(xún)時(shí),可能會(huì)出現(xiàn)語(yǔ)法錯(cuò)誤的情況。 條件查詢(xún)API提供了創(chuàng)建具有編譯時(shí)安全性的結(jié)構(gòu)化和嵌套查詢(xún)的功能。 進(jìn)入有關(guān)標(biāo)準(zhǔn)查詢(xún)的更多理論可能不是一個(gè)好主意,因?yàn)榭梢栽诰W(wǎng)上找到大量相同的頁(yè)面。 讓我們舉一個(gè)簡(jiǎn)單的例子來(lái)了解使用條件查詢(xún)的查詢(xún)。 在這篇文章中,我將Hibernate作為JPA 2.0的供應(yīng)商來(lái)展示Criteria Query的示例。 在深入探討標(biāo)準(zhǔn)查詢(xún)之前,讓我們考慮一下可以表示為實(shí)體的數(shù)據(jù)庫(kù)表和相應(yīng)的Java類(lèi):

數(shù)據(jù)庫(kù)表:

例如,下面有兩個(gè)數(shù)據(jù)庫(kù)表:

  • 狀態(tài)[stateId,stateName]
  • 城市[cityId,stateId(FK#),CityName]
  • 我們要獲取特定州的城市列表,在該州中,城市名稱(chēng)應(yīng)從“ M”開(kāi)始,城市列表應(yīng)按升序排列。 如果我們考慮簡(jiǎn)單的本機(jī)SQL,則如下所示: Select * from City c, State s where c.stateId = s.stateId and c.stateId = ? and c.cityName like "M%" order by c.cityName

    JPA實(shí)體:

    以下是配置為JPA實(shí)體以表示州和城市表的兩個(gè)Java類(lèi)。 這些也可以使用逆向工程工具生成。

    STATE表的Java實(shí)體

    import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import java.util.Date; import java.util.Set; import javax.persistence.SequenceGenerator;@Entity @Table(name="STATE") @SequenceGenerator(sequenceName="STATE_SEQ",name="STATE_SEQ_GEN") public class State {private Long stateId;private String stateName;private Set citySet;@Id@Column(name="stateId")@GeneratedValue(generator="STATE_SEQ_GEN",strategy=GenerationType.SEQUENCE)public Long getStateId;() {return stateId;}public void setId(long stateId) {stateId = stateId;}@Column(name="stateName")public String getStateName() {return stateName;}public void setStateName(String stateName) {this.stateName = stateName;}public void setCitySet(Set citySet)this.citySet= citySet;}@OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL,mappedBy="state")public Set getCitySet() {return citySet;} }

    CITY表的Java實(shí)體

    import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table;@Entity @Table(name="CITY") @SequenceGenerator(sequenceName="CITY_SEQ",name="CITY_SEQ_GEN") public class City {private Long cityId;private String cityName;private State state;public void setId(long cityId) {this.cityId = cityId;}@Id@Column(name="CityId")@GeneratedValue(generator="CITY_SEQ_GEN",strategy=GenerationType.SEQUENCE)public Long getCityId() {return cityId;}@Column(name="CityName")public void setContent(String cityName) {this.cityName = cityName;}public String getCityName() {return cityName;}public void setState(State state) {this.state = state;}@ManyToOne(fetch = FetchType.LAZY)@JoinColumn(name = "STATEID", nullable = false)public state getState() {return state;} }

    值對(duì)象(PO??JO):

    以下是兩個(gè)值對(duì)象。 借助條件查詢(xún),您可以直接從結(jié)果數(shù)據(jù)映射值對(duì)象。 您無(wú)需編寫(xiě)代碼即可將結(jié)果數(shù)據(jù)從實(shí)體類(lèi)復(fù)制到value對(duì)象。 這確實(shí)是條件查詢(xún)中令人興奮的功能。 public class StateVO {private Long stateId;private String stateName;private Set cityVOSet;// All getter setters} public class CityVO {private Long cityId;private String cityName;private StateVO stateVO;public CityVO( Long cityId, String cityName){this.cityId=cicityId;this.cityName=cityName;}// All getter setters }

    DAO實(shí)施:

    現(xiàn)在是時(shí)候使用標(biāo)準(zhǔn)查詢(xún)來(lái)獲取數(shù)據(jù)了。 我們將公開(kāi)一個(gè)將輸入?yún)?shù)作為StateVO并返回CityVO列表的方法。 import javax.persistence.EntityManager;import javax.persistence.EntityManagerFactory;import javax.persistence.Persistence;public class StateCityDAOImpl{public List getCityList(StateVO searchStateVO) {// Get the entity manager instanceEntityManagerFactory emf = Persistence.createEntityManagerFactory("StateCityService");EntityManager entityManager= emf.createEntityManager();// Get the criteria builder instance from entity managerfinal CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();// Create criteria query and pass the value object which needs to be populated as resultfinal CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(CityVO.class);// Tell to criteria query which tables/entities you want to fetch// To join the City and State tables, we need to write below codefinal Root stateRoot = criteriaQuery.from(State.class);final Root cityRoot = criteriaQuery.from(City.class);// Time to define where clause in terms of Predicates// This list will contain all Predicates (where clauses)List criteriaList = new ArrayList();// Note: Ensure that whatever string you are passing in root variables// It should be matched with variables' name in entity classes// [1] where condition: State.StateId = City.StateIdPredicate predicate1 = criteriaBuilder.equal(cityRoot. get("state"). get("stateId"),stateRoot. get("stateId"));criteriaList.add(predicate1);// [2] where condition: City.StateId = ?if (searchStateVO.getStateId() != null) {Predicate predicate2= criteriaBuilder.equal(cityRoot. get("state"). get("stateId"),searchStateVO.getStateId());criteriaList.add(predicate2);}// [3] where condition: City.cityName like 'M%'Predicate predicate3= criteriaBuilder.like(criteriaBuilder.upper(cityRoot. get("cityName")),"M%");criteriaList.add(predicate3); // This statement maps your CityVO with result data// You have to have a custom constructor in CityVO (see above) to populate the result data criteriaQuery.select(criteriaBuilder.construct(CityVO.class, cityRoot. get("cityId"),cityRoot. get("cityName")));// Pass the criteria list to the where method of criteria querycriteriaQuery.where(criteriaBuilder.and(criteriaList.toArray(new Predicate[0])));// Order by clause based on city namescriteriaQuery.orderBy(criteriaBuilder.asc(cityRoot. get("cityName")));// Here entity manager will create actual SQL query out of criteria queryfinal TypedQuery query = entityManager.createQuery(criteriaQuery);// This code can be used to define the row range to fetch the result/* if (CitySize != 0) {query.setFirstResult(startIndex); // starting row indexquery.setMaxResults(endIndex); // end row index}*/return query.getResultList();} 現(xiàn)在我們有了CityVO清單作為您的答案。 我們可以根據(jù)上述要求訪問(wèn)相應(yīng)的城市名稱(chēng)。 雖然,使用條件查詢(xún)編寫(xiě)查詢(xún)可能有點(diǎn)笨拙,但是一旦使用方便,您就會(huì)喜歡“條件查詢(xún)”。

    參考:我們的JCG合作伙伴 Narendra Verma在NS.Infra博客上的《 使用Hibernate進(jìn)行JPA 2.0標(biāo)準(zhǔn)查詢(xún)》 。

    翻譯自: https://www.javacodegeeks.com/2013/04/jpa-2-0-criteria-query-with-hibernate.html

    總結(jié)

    以上是生活随笔為你收集整理的使用Hibernate的JPA 2.0标准查询的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

    如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。