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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

005_Spring Data JPA条件查询

發布時間:2025/5/22 javascript 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 005_Spring Data JPA条件查询 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1. 創建一個名為spring-data-jpa-specification-executor的Java項目, 同時添加相關jar包, 并添加JUnit能力。

2. 查看JpaSpecificationExecutor接口下的方法?

3. 新建User.java?

package com.bjbs.pojo;import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.springframework.format.annotation.DateTimeFormat;@Entity // 指定該類是實體類 @Table(name = "user") // 指定數據庫表名(表名和實體類對應) public class User implements Serializable {private static final long serialVersionUID = 1L;@Id // 指定為主鍵@GeneratedValue(strategy = GenerationType.IDENTITY) // 指定主鍵生成策略@Column(name = "id") // 指定表中列名(列名和屬性名對應)private Integer id;@Column(name = "name")private String name;@Column(name = "sex")private String sex;@Column(name = "birthday")@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Date birthday;@Column(name = "address")private String address;public User() {}public User(String name, String sex, Date birthday, String address) {this.name = name;this.sex = sex;this.birthday = birthday;this.address = address;}public User(Integer id, String name, String sex, Date birthday, String address) {this.id = id;this.name = name;this.sex = sex;this.birthday = birthday;this.address = address;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}@Overridepublic String toString() {return "User [id=" + id + ", name=" + name + ", sex=" + sex + ", birthday=" + birthday + ", address=" + address+ "]";} }

4. 新建UserRepository.java, 實現Repository和JpaSpecificationExecutor接口。

package com.bjbs.dao;import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.Repository; import com.bjbs.pojo.User;/*** 參數一T: 當前需要映射的實體; 參數二 T: 當前映射的實體中的id的類型*/ public interface UserRepository extends Repository<User, Integer>, JpaSpecificationExecutor<User> {}

5. 新建UserService.java

package com.bjbs.service;import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import com.bjbs.pojo.User;public interface UserService {public User findOne(Specification<User> spec);public List<User> findAll(Specification<User> spec);public Page<User> findAll(Specification<User> spec, Pageable pageable);public List<User> findAll(Specification<User> spec, Sort sort); }

6. 新建UserServiceImpl.java

package com.bjbs.service.impl;import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.bjbs.dao.UserRepository; import com.bjbs.pojo.User; import com.bjbs.service.UserService;@Service @Transactional public class UserServiceImpl implements UserService {@Autowiredprivate UserRepository userRepository;@Overridepublic User findOne(Specification<User> spec) {return userRepository.findOne(spec);}@Overridepublic List<User> findAll(Specification<User> spec) {return userRepository.findAll(spec);}@Overridepublic Page<User> findAll(Specification<User> spec, Pageable pageable) {return userRepository.findAll(spec, pageable);}@Overridepublic List<User> findAll(Specification<User> spec, Sort sort) {return userRepository.findAll(spec, sort);}}

7. 新建TestUserRepository.java

package com.bjbs.test;import java.util.ArrayList; import java.util.List; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.jpa.domain.Specification; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.bjbs.pojo.User; import com.bjbs.service.UserService;@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class TestUserRepository {@Autowiredprivate UserService userService;/*** 查詢名字叫'曹操'的用戶*/@Testpublic void findOne() {Specification<User> spe = new Specification<User>() {/*** @return Predicate: 定義了查詢條件。* @param Root<Users> root: 根對象, 封裝了查詢條件的對象。* @param CriteriaQuery<?> query: 定義了一個基本的查詢, 一般不使用。* @param CriteriaBuilder cb: 創建一個查詢條件。*/@Overridepublic Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {Predicate pre = cb.equal(root.get("name"), "曹操");return pre;}};User userDb = userService.findOne(spe);System.out.println(userDb);}/*** 查詢名字叫'曹操'和性別為'男'的用戶*/@Testpublic void findOneByNameAndSex() {Specification<User> spe = new Specification<User>() {@Overridepublic Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {List<Predicate> list = new ArrayList<Predicate>();list.add(cb.equal(root.get("name"), "曹操"));list.add(cb.equal(root.get("sex"), "男"));Predicate[] arr = new Predicate[list.size()];return cb.and(list.toArray(arr));}};User userDb = userService.findOne(spe);System.out.println(userDb);}/*** 查詢名字叫'曹操'和住址為'安徽省亳州市'的用戶*/@Testpublic void findOneByNameAndAddress() {Specification<User> spe = new Specification<User>() {@Overridepublic Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {return cb.and(cb.equal(root.get("name"), "曹操"), cb.equal(root.get("address"), "安徽省亳州市"));}};User userDb = userService.findOne(spe);System.out.println(userDb);}/*** 查詢名字叫'曹操'或'曹植'的用戶*/@Testpublic void findByNameOr() {Specification<User> spe = new Specification<User>() {@Overridepublic Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {return cb.or(cb.equal(root.get("name"), "曹操"), cb.equal(root.get("name"), "曹植"));}};List<User> list = userService.findAll(spe);for (User user : list) {System.out.println(user);}}/*** 查詢姓李的用戶*/@Testpublic void findByNameLike() {Specification<User> spe = new Specification<User>() {@Overridepublic Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {return cb.like(root.get("name"), "李%");}};List<User> list = userService.findAll(spe);for (User user : list) {System.out.println(user);}}/*** 分頁查詢id在47和51之間的用戶*/@Testpublic void pageable() {Specification<User> spe = new Specification<User>() {@Overridepublic Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {return cb.between(root.get("id"), 47, 51);}};Pageable pageable = new PageRequest(0, 5);Page<User> list = userService.findAll(spe, pageable);for (User user : list) {System.out.println(user);}}/*** 排序查詢id>51*/@Testpublic void sort() {Specification<User> spe = new Specification<User>() {@Overridepublic Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {return cb.greaterThan(root.get("id"), 51);}};Sort sort = new Sort(Direction.DESC, "id");List<User> list = userService.findAll(spe, sort);for (User user : list) {System.out.println(user);}}/*** 分頁排序查詢id>=51*/@Testpublic void pageableAndSort() {Specification<User> spe = new Specification<User>() {@Overridepublic Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {return cb.ge(root.get("id"), 51);}};Sort sort = new Sort(Direction.DESC, "id");Pageable pageable = new PageRequest(0, 3, sort);Page<User> list = userService.findAll(spe, pageable);for (User user : list) {System.out.println(user);}} }

8. 在src下新建application.properties

spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://192.168.25.138:3306/StudyMybatis?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=lyw123456

9. 在src下新建applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:jpa="http://www.springframework.org/schema/data/jpa"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><!-- 配置讀取properties文件的工具類 --><context:property-placeholder location="classpath:application.properties" /><!-- 配置c3p0數據庫連接池 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="jdbcUrl" value="${spring.datasource.url}" /><property name="driverClass" value="${spring.datasource.driverClassName}" /><property name="user" value="${spring.datasource.username}" /><property name="password" value="${spring.datasource.password}" /></bean><!-- Spring整合JPA 配置EntityManagerFactory --><bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"><property name="dataSource" ref="dataSource" /><property name="jpaVendorAdapter"><bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"><!-- hibernate相關的屬性的注入 --><!-- 配置數據庫類型 --><property name="database" value="MYSQL" /><!-- 正向工程 自動創建表 --><!-- <property name="generateDdl" value="true" /> --><!-- 顯示執行的SQL --><property name="showSql" value="true" /></bean></property><!-- 掃描實體的包 --><property name="packagesToScan"><list><value>com.bjbs.pojo</value></list></property></bean><!-- 配置Hibernate的事務管理器 --><bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"><property name="entityManagerFactory" ref="entityManagerFactory" /></bean><!-- 配置開啟注解事務處理 --><tx:annotation-driven transaction-manager="transactionManager" /><!-- 配置springIOC的注解掃描 --><context:component-scan base-package="com.bjbs.service" /><!-- Spring Data JPA 的配置 --><!-- base-package: 掃描dao接口所在的包 --><jpa:repositories base-package="com.bjbs.dao" /> </beans>

10. 數據庫user表

11. 查詢名字叫'曹操'的用戶?

12. 查詢名字叫'曹操'和性別為'男'的用戶?

13. 查詢名字叫'曹操'和住址為'安徽省亳州市'的用戶?

14. 查詢名字叫'曹操'或'曹植'的用戶?

15. 查詢姓'李'的用戶?

16. 分頁查詢id在47和51之間的用戶?

17. 排序查詢id>51?

18. 分頁排序查詢id>=51?

總結

以上是生活随笔為你收集整理的005_Spring Data JPA条件查询的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。