您好,登錄后才能下訂單哦!
小編給大家分享一下spring boot jpa如何整合QueryDSL來(lái)簡(jiǎn)化復(fù)雜操作,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
前言
使用過(guò)spring data jpa的同學(xué),都很清楚,對(duì)于復(fù)雜的sql查詢,處理起來(lái)還是比較復(fù)雜的,而本文中的QueryDSL就是用來(lái)簡(jiǎn)化JPA操作的。
Querydsl定義了一種常用的靜態(tài)類型語(yǔ)法,用于在持久域模型數(shù)據(jù)之上進(jìn)行查詢。JDO和JPA是Querydsl的主要集成技術(shù)。本文旨在介紹如何使用Querydsl與JPA組合使用。JPA的Querydsl是JPQL和Criteria查詢的替代方法。QueryDSL僅僅是一個(gè)通用的查詢框架,專注于通過(guò)Java API構(gòu)建類型安全的SQL查詢。
要想使用QueryDSL,需要做兩個(gè)前提操作:
1、pom文件中,加入依賴
<!--query dsl --> <dependency> <groupId>com.querydsl</groupId> <artifactId>querydsl-jpa</artifactId> </dependency> <dependency> <groupId>com.querydsl</groupId> <artifactId>querydsl-apt</artifactId> <scope>provided</scope> </dependency>
2、pom文件中,加入編譯插件
<plugin> <groupId>com.mysema.maven</groupId> <artifactId>apt-maven-plugin</artifactId> <version>1.1.3</version> <executions> <execution> <goals> <goal>process</goal> </goals> <configuration> <outputDirectory>target/generated-sources/java</outputDirectory> <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor> </configuration> </execution> </executions> </plugin>
該插件會(huì)查找使用javax.persistence.Entity注解的域類型,并為它們生成對(duì)應(yīng)的查詢類型。下面以User實(shí)體類來(lái)說(shuō)明,生成的查詢類型如下:
package com.chhliu.springboot.jpa.entity; import static com.querydsl.core.types.PathMetadataFactory.*; import com.querydsl.core.types.dsl.*; import com.querydsl.core.types.PathMetadata; import javax.annotation.Generated; import com.querydsl.core.types.Path; /** * QUser is a Querydsl query type for User */ @Generated("com.querydsl.codegen.EntitySerializer") public class QUser extends EntityPathBase<User> { private static final long serialVersionUID = 1153899872L; public static final QUser user = new QUser("user"); public final StringPath address = createString("address"); public final NumberPath<Integer> age = createNumber("age", Integer.class); public final NumberPath<Integer> id = createNumber("id", Integer.class); public final StringPath name = createString("name"); public QUser(String variable) { super(User.class, forVariable(variable)); } public QUser(Path<? extends User> path) { super(path.getType(), path.getMetadata()); } public QUser(PathMetadata metadata) { super(User.class, metadata); } }
我們建立好實(shí)體類之后,然后運(yùn)行mvn clean complie命令,就會(huì)在
<outputDirectory>target/generated-sources/java</outputDirectory>
目錄下生成對(duì)應(yīng)的查詢類型。然后將生成的類都拷貝到項(xiàng)目中,即可。
本文涉及到的Entity如下:
package com.chhliu.springboot.jpa.entity; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="t_user") public class User implements Serializable{ /** * */ private static final long serialVersionUID = 1L; @Id() @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String name; private String address; private int age; …………省略getter,setter方法………… /** * attention: * Details:方便查看測(cè)試結(jié)果 * @author chhliu */ @Override public String toString() { return "User [id=" + id + ", name=" + name + ", address=" + address + ", age=" + age + "]"; } }
上面的這個(gè)實(shí)體類,主要用于單表操作。
package com.chhliu.springboot.jpa.entity; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Table; /** * 描述:TODO * @author chhliu */ @Entity @Table(name="PERSON") public class Person { @Id @GeneratedValue private Integer id; private String name; private String address; @OneToOne(mappedBy="person", cascade={CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.MERGE}) private IDCard idCard; …………省略getter,setter方法………… @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", address=" + address + ", idCard=" + idCard + "]"; } }
package com.chhliu.springboot.jpa.entity; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Table; /** * 描述: * @author chhliu */ @Entity @Table(name="IDCARD") public class IDCard { @Id @GeneratedValue private Integer id; private String idNo; @OneToOne(cascade={CascadeType.MERGE, CascadeType.REMOVE, CascadeType.PERSIST}, fetch=FetchType.EAGER) private Person person; …………省略getter,setter方法………… @Override public String toString() { return "IDCard [id=" + id + ", idNo=" + idNo + ", person=" + person + "]"; } }
上面兩個(gè)Entity主要用于一對(duì)一關(guān)系的示例操作
package com.chhliu.springboot.jpa.entity; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; /** * 描述:Order實(shí)體類 * @author chhliu */ @Entity @Table(name="ORDER_C") public class Order { @Id @GeneratedValue @Column(name="ID") private Integer id; @Column(length=20, name="ORDER_NAME") private String orderName; @Column(name="COUNT") private Integer count; @OneToMany(mappedBy = "order",cascade={CascadeType.PERSIST,CascadeType.REMOVE},fetch = FetchType.EAGER) private List<OrderItem> orderItems; …………省略getter,setter方法………… }
package com.chhliu.springboot.jpa.entity; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * 描述:OrderItem實(shí)體類 * @author chhliu */ @Entity @Table(name="ORDER_ITEM") public class OrderItem { @Id @GeneratedValue @Column(name="ID", nullable=false) private Integer id; @Column(name="ITEM_NAME", length=20) private String itemName; @Column(name="PRICE") private Integer price; @ManyToOne(cascade={CascadeType.PERSIST,CascadeType.REMOVE, CascadeType.MERGE}, fetch=FetchType.EAGER) @JoinColumn(name = "ORDER_ID") private Order order; …………省略getter,setter方法………… }
上面兩個(gè)Entity用于展示一對(duì)多關(guān)系的示例操作。
首先,我們來(lái)看單表操作
1、使用spring data jpa
要想使用spring data jpa提供的QueryDSL功能,很簡(jiǎn)單,直接繼承接口即可。Spring Data JPA中提供了QueryDslPredicateExecutor接口,用于支持QueryDSL的查詢操作接口,如下:
package com.chhliu.springboot.jpa.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.querydsl.QueryDslPredicateExecutor; import com.chhliu.springboot.jpa.entity.User; public interface UserRepositoryDls extends JpaRepository<User, Integer>, QueryDslPredicateExecutor<User>{ // 繼承接口 }
QueryDslPredicateExecutor接口提供了如下方法:
public interface QueryDslPredicateExecutor<T> { T findOne(Predicate predicate); Iterable<T> findAll(Predicate predicate); Iterable<T> findAll(Predicate predicate, Sort sort); Iterable<T> findAll(Predicate predicate, OrderSpecifier<?>... orders); Iterable<T> findAll(OrderSpecifier<?>... orders); Page<T> findAll(Predicate predicate, Pageable pageable); long count(Predicate predicate); boolean exists(Predicate predicate); }
以上方法的使用和spring data jpa中的其他接口使用方法類似,詳情請(qǐng)參考:https://www.jb51.net/article/137757.htm
測(cè)試如下:
public User findUserByUserName(final String userName){ /** * 該例是使用spring data QueryDSL實(shí)現(xiàn) */ QUser quser = QUser.user; Predicate predicate = quser.name.eq(userName);// 根據(jù)用戶名,查詢user表 return repository.findOne(predicate); }
對(duì)應(yīng)的sql如下:
復(fù)制代碼 代碼如下:
select user0_.id as id1_5_, user0_.address as address2_5_, user0_.age as age3_5_, user0_.name as name4_5_ from t_user user0_ where user0_.name=?
單表操作示例代碼如下:
package com.chhliu.springboot.jpa.repository; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Component; import com.chhliu.springboot.jpa.entity.QUser; import com.chhliu.springboot.jpa.entity.User; import com.querydsl.core.types.Predicate; import com.querydsl.jpa.impl.JPAQueryFactory; /** * 描述:QueryDSL JPA * @author chhliu */ @Component @Transactional public class UserRepositoryManagerDsl { @Autowired private UserRepositoryDls repository; @Autowired @PersistenceContext private EntityManager entityManager; private JPAQueryFactory queryFactory; @PostConstruct public void init() { queryFactory = new JPAQueryFactory(entityManager); } public User findUserByUserName(final String userName){ /** * 該例是使用spring data QueryDSL實(shí)現(xiàn) */ QUser quser = QUser.user; Predicate predicate = quser.name.eq(userName); return repository.findOne(predicate); } /** * attention: * Details:查詢user表中的所有記錄 */ public List<User> findAll(){ QUser quser = QUser.user; return queryFactory.selectFrom(quser) .fetch(); } /** * Details:?jiǎn)螚l件查詢 */ public User findOneByUserName(final String userName){ QUser quser = QUser.user; return queryFactory.selectFrom(quser) .where(quser.name.eq(userName)) .fetchOne(); } /** * Details:?jiǎn)伪矶鄺l件查詢 */ public User findOneByUserNameAndAddress(final String userName, final String address){ QUser quser = QUser.user; return queryFactory.select(quser) .from(quser) // 上面兩句代碼等價(jià)與selectFrom .where(quser.name.eq(userName).and(quser.address.eq(address)))// 這句代碼等同于where(quser.name.eq(userName), quser.address.eq(address)) .fetchOne(); } /** * Details:使用join查詢 */ public List<User> findUsersByJoin(){ QUser quser = QUser.user; QUser userName = new QUser("name"); return queryFactory.selectFrom(quser) .innerJoin(quser) .on(quser.id.intValue().eq(userName.id.intValue())) .fetch(); } /** * Details:將查詢結(jié)果排序 */ public List<User> findUserAndOrder(){ QUser quser = QUser.user; return queryFactory.selectFrom(quser) .orderBy(quser.id.desc()) .fetch(); } /** * Details:Group By使用 */ public List<String> findUserByGroup(){ QUser quser = QUser.user; return queryFactory.select(quser.name) .from(quser) .groupBy(quser.name) .fetch(); } /** * Details:刪除用戶 */ public long deleteUser(String userName){ QUser quser = QUser.user; return queryFactory.delete(quser).where(quser.name.eq(userName)).execute(); } /** * Details:更新記錄 */ public long updateUser(final User u, final String userName){ QUser quser = QUser.user; return queryFactory.update(quser).where(quser.name.eq(userName)) .set(quser.name, u.getName()) .set(quser.age, u.getAge()) .set(quser.address, u.getAddress()) .execute(); } /** * Details:使用原生Query */ public User findOneUserByOriginalSql(final String userName){ QUser quser = QUser.user; Query query = queryFactory.selectFrom(quser) .where(quser.name.eq(userName)).createQuery(); return (User) query.getSingleResult(); } /** * Details:分頁(yè)查詢單表 */ public Page<User> findAllAndPager(final int offset, final int pageSize){ Predicate predicate = QUser.user.id.lt(10); Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "id")); PageRequest pr = new PageRequest(offset, pageSize, sort); return repository.findAll(predicate, pr); } }
多表操作示例(一對(duì)一)如下:
package com.chhliu.springboot.jpa.repository; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.chhliu.springboot.jpa.dto.PersonIDCardDto; import com.chhliu.springboot.jpa.entity.QIDCard; import com.chhliu.springboot.jpa.entity.QPerson; import com.querydsl.core.QueryResults; import com.querydsl.core.Tuple; import com.querydsl.core.types.Predicate; import com.querydsl.jpa.impl.JPAQuery; import com.querydsl.jpa.impl.JPAQueryFactory; @Component public class PersonAndIDCardManager { @Autowired @PersistenceContext private EntityManager entityManager; private JPAQueryFactory queryFactory; @PostConstruct public void init() { queryFactory = new JPAQueryFactory(entityManager); } /** * Details:多表動(dòng)態(tài)查詢 */ public List<Tuple> findAllPersonAndIdCard(){ Predicate predicate = (QPerson.person.id.intValue()).eq(QIDCard.iDCard.person.id.intValue()); JPAQuery<Tuple> jpaQuery = queryFactory.select(QIDCard.iDCard.idNo, QPerson.person.address, QPerson.person.name) .from(QIDCard.iDCard, QPerson.person) .where(predicate); return jpaQuery.fetch(); } /** * Details:將查詢結(jié)果以DTO的方式輸出 */ public List<PersonIDCardDto> findByDTO(){ Predicate predicate = (QPerson.person.id.intValue()).eq(QIDCard.iDCard.person.id.intValue()); JPAQuery<Tuple> jpaQuery = queryFactory.select(QIDCard.iDCard.idNo, QPerson.person.address, QPerson.person.name) .from(QIDCard.iDCard, QPerson.person) .where(predicate); List<Tuple> tuples = jpaQuery.fetch(); List<PersonIDCardDto> dtos = new ArrayList<PersonIDCardDto>(); if(null != tuples && !tuples.isEmpty()){ for(Tuple tuple:tuples){ String address = tuple.get(QPerson.person.address); String name = tuple.get(QPerson.person.name); String idCard = tuple.get(QIDCard.iDCard.idNo); PersonIDCardDto dto = new PersonIDCardDto(); dto.setAddress(address); dto.setIdNo(idCard); dto.setName(name); dtos.add(dto); } } return dtos; } /** * Details:多表動(dòng)態(tài)查詢,并分頁(yè) */ public QueryResults<Tuple> findByDtoAndPager(int offset, int pageSize){ Predicate predicate = (QPerson.person.id.intValue()).eq(QIDCard.iDCard.person.id.intValue()); return queryFactory.select(QIDCard.iDCard.idNo, QPerson.person.address, QPerson.person.name) .from(QIDCard.iDCard, QPerson.person) .where(predicate) .offset(offset) .limit(pageSize) .fetchResults(); } }
上面將查詢結(jié)果以DTO的方式輸出的示例中,在查詢結(jié)束后,將查詢結(jié)果手動(dòng)的轉(zhuǎn)換成了DTO對(duì)象,這種方式其實(shí)不太優(yōu)雅,QueryDSL給我們提供了更好的方式,見(jiàn)下面的示例:
/** * Details:方式一:使用Bean投影 */ public List<PersonIDCardDto> findByDTOUseBean(){ Predicate predicate = (QPerson.person.id.intValue()).eq(QIDCard.iDCard.person.id.intValue()); return queryFactory.select( Projections.bean(PersonIDCardDto.class, QIDCard.iDCard.idNo, QPerson.person.address, QPerson.person.name)) .from(QIDCard.iDCard, QPerson.person) .where(predicate) .fetch(); } /** * Details:方式二:使用fields來(lái)代替setter */ public List<PersonIDCardDto> findByDTOUseFields(){ Predicate predicate = (QPerson.person.id.intValue()).eq(QIDCard.iDCard.person.id.intValue()); return queryFactory.select( Projections.fields(PersonIDCardDto.class, QIDCard.iDCard.idNo, QPerson.person.address, QPerson.person.name)) .from(QIDCard.iDCard, QPerson.person) .where(predicate) .fetch(); } /** * Details:方式三:使用構(gòu)造方法,注意構(gòu)造方法中屬性的順序必須和構(gòu)造器中的順序一致 */ public List<PersonIDCardDto> findByDTOUseConstructor(){ Predicate predicate = (QPerson.person.id.intValue()).eq(QIDCard.iDCard.person.id.intValue()); return queryFactory.select( Projections.constructor(PersonIDCardDto.class, QPerson.person.name, QPerson.person.address, QIDCard.iDCard.idNo)) .from(QIDCard.iDCard, QPerson.person) .where(predicate) .fetch(); }
上面只是提供了幾種思路,當(dāng)然,還可以使用@QueryProjection來(lái)實(shí)現(xiàn),非常靈活。
一對(duì)多示例:
package com.chhliu.springboot.jpa.repository; import java.util.List; import javax.annotation.PostConstruct; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.chhliu.springboot.jpa.entity.QOrder; import com.chhliu.springboot.jpa.entity.QOrderItem; import com.querydsl.core.Tuple; import com.querydsl.core.types.Predicate; import com.querydsl.jpa.impl.JPAQuery; import com.querydsl.jpa.impl.JPAQueryFactory; @Component public class OrderAndOrderItemManager { @Autowired @PersistenceContext private EntityManager entityManager; private JPAQueryFactory queryFactory; @PostConstruct public void init() { queryFactory = new JPAQueryFactory(entityManager); } /** * Details:一對(duì)多,條件查詢 */ public List<Tuple> findOrderAndOrderItemByOrderName(String orderName){ //添加查詢條件 Predicate predicate = QOrder.order.orderName.eq(orderName); JPAQuery<Tuple> jpaQuery = queryFactory.select(QOrder.order, QOrderItem.orderItem) .from(QOrder.order, QOrderItem.orderItem) .where(QOrderItem.orderItem.order.id.intValue().eq(QOrder.order.id.intValue()), predicate); //拿到結(jié)果 return jpaQuery.fetch(); } /** * Details:多表連接查詢 */ public List<Tuple> findAllByOrderName(String orderName){ //添加查詢條件 Predicate predicate = QOrder.order.orderName.eq(orderName); JPAQuery<Tuple> jpaQuery = queryFactory.select(QOrder.order, QOrderItem.orderItem) .from(QOrder.order, QOrderItem.orderItem) .rightJoin(QOrder.order) .on(QOrderItem.orderItem.order.id.intValue().eq(QOrder.order.id.intValue())); jpaQuery.where(predicate); //拿到結(jié)果 return jpaQuery.fetch(); } }
從上面的示例中,我們可以看出,QueryDSL大大的簡(jiǎn)化了我們的操作
以上是“spring boot jpa如何整合QueryDSL來(lái)簡(jiǎn)化復(fù)雜操作”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。