springboot集成jpa操作mybatis数据库
数据库如下
CREATE TABLE `jpa`.`Untitled` ( `cust_id` bigint(20) NOT NULL AUTO_INCREMENT, `cust_address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `cust_industry` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `cust_level` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `cust_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `cust_phone` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `cust_source` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, PRIMARY KEY (`cust_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 10 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
CREATE TABLE `jpa`.`Untitled` ( `lkm_id` bigint(20) NOT NULL AUTO_INCREMENT, `lkm_email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `lkm_gender` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `lkm_memo` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `lkm_mobile` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `lkm_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `lkm_phone` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `lkm_position` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `lkm_qq` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `lkm_cust_id` bigint(20) DEFAULT NULL, PRIMARY KEY (`lkm_id`) USING BTREE, INDEX `FKh9yp1nql5227xxcopuxqx2e7q`(`lkm_cust_id`) USING BTREE, CONSTRAINT `FKh9yp1nql5227xxcopuxqx2e7q` FOREIGN KEY (`lkm_cust_id`) REFERENCES `jpa`.`cst_customer` (`cust_id`) ON DELETE RESTRICT ON UPDATE RESTRICT ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
CREATE TABLE `jpa`.`Untitled` ( `id` int(11) NOT NULL AUTO_INCREMENT, `city` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `province` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
CREATE TABLE `jpa`.`Untitled` ( `id` int(11) NOT NULL AUTO_INCREMENT, `birth` datetime(0) DEFAULT NULL, `email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `last_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `address_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE, INDEX `FK_56686o67ve8p9x4eew6bhebdb`(`address_id`) USING BTREE, CONSTRAINT `FK_56686o67ve8p9x4eew6bhebdb` FOREIGN KEY (`address_id`) REFERENCES `jpa`.`jpa_addresses` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT ) ENGINE = InnoDB AUTO_INCREMENT = 201 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
接下来就是maven依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tuling.cloud</groupId> <artifactId>microservice-provider-user</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <!-- 引入spring boot的依赖 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> </dependencies> <!-- 引入spring cloud的依赖 --> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Edgware.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <!-- 添加spring-boot的maven插件 --> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
一:相关jar依赖添加
因为使用到了mysql,在POM.XML文件中引入mysql相关jar及操作数据库相关的。这里我们使用的是spring-jpa来操作数据库。具体jra如下:
<!-- mysql 相关的依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- jpa相关依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
点击更新就可以了。
二:数据库连接配置。这里我们使用的是yml格式的。配置如下图:
server: port: 8002 spring: application: name: microservice-provider-user jpa: generate-ddl: false show-sql: true hibernate: ddl-auto: none datasource: # 指定数据源 driver-class-name: com.mysql.jdbc.Driver # 指定数据源类型 username: root # 指定h2数据库的建表脚本 password: 123456 # 指定h2数据库的数据脚本 url: jdbc:mysql://localhost/jpa?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false logging: # 配置日志级别,让hibernate打印出执行的SQL level: root: INFO org.hibernate: INFO org.hibernate.type.descriptor.sql.BasicBinder: TRACE org.hibernate.type.descriptor.sql.BasicExtractor: TRACE eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/ instance: prefer-ip-address: true
说明:
spring.jpa.show-sql=true.这句意思是:打印sql语句。
在url后面添加serverTimeizone=UTC是为了解决时区错误的问题。
注意点1:数据库驱动包的类型
三:创建实体及测试
3.1:创建ProductCategory实体对象。使用spring-jpa方式:
package com.tuling.cloud.study.entity; import java.util.HashSet; import java.util.Set; 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.OneToMany; import javax.persistence.Table; @Entity // 声明此类是个实体类 需要导入javax.persistence.Entity; @Table(name = "cst_customer") //需要将该类对应到数据库中的哪一个表中,name中填表的名称 public class Customer { @Id //声明主键 @GeneratedValue(strategy = GenerationType.IDENTITY) //声明主键的生成策略为自动递增 //mysql使用自增模式,orcle 使用序列模式 @Column(name = "cust_id") //设置该属性和数据库中的哪一个字段对应 private Long custId; @Column(name = "cust_name") private String custName; @Column(name = "cust_source") private String custSource; @Column(name = "cust_level") private String custLevel; @Column(name = "cust_industry") private String cusIndustry; @Column(name = "cust_phone") private String custPhone; @Column(name = "cust_address") private String custAddress; @OneToMany(targetEntity=LinkMan.class) @JoinColumn(name="lkm_cust_id",referencedColumnName="cust_id") private Set<LinkMan> linkMans = new HashSet<LinkMan>(); public Long getCustId() { return custId; } public void setCustId(Long custId) { this.custId = custId; } public String getCustName() { return custName; } public void setCustName(String custName) { this.custName = custName; } public String getCustSource() { return custSource; } public void setCustSource(String custSource) { this.custSource = custSource; } public String getCustLevel() { return custLevel; } public void setCustLevel(String custLevel) { this.custLevel = custLevel; } public String getCusIndustry() { return cusIndustry; } public void setCusIndustry(String cusIndustry) { this.cusIndustry = cusIndustry; } public String getCustPhone() { return custPhone; } public void setCustPhone(String custPhone) { this.custPhone = custPhone; } public String getCustAddress() { return custAddress; } public void setCustAddress(String custAddress) { this.custAddress = custAddress; } @Override public String toString() { return "Customer [custId=" + custId + ", custName=" + custName + ", custSource=" + custSource + ", custLevel=" + custLevel + ", cusIndustry=" + cusIndustry + ", custPhone=" + custPhone + ", custAddress=" + custAddress + "]"; } public Set<LinkMan> getLinkMans() { return linkMans; } public void setLinkMans(Set<LinkMan> linkMans) { this.linkMans = linkMans; } }
package com.tuling.cloud.study.entity; 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.OneToMany; import javax.persistence.Table; @Entity // 声明此类是个实体类 需要导入javax.persistence.Entity; @Table(name = "cst_linkman") //需要将该类对应到数据库中的哪一个表中,name中填表的名称 public class LinkMan { @Id //声明主键 @GeneratedValue(strategy = GenerationType.IDENTITY) //声明主键的生成策略为自动递增 @Column(name = "lkm_id") //设置该属性和数据库中的哪一个字段对应 private Long lkmId; @Column(name = "lkm_gender") //设置该属性和数据库中的哪一个字段对应 private Character lkmGender; @Column(name = "lkm_name") //设置该属性和数据库中的哪一个字段对应 private String lkmName; @Column(name = "lkm_phone") //设置该属性和数据库中的哪一个字段对应 private String lkmPhone; @Column(name = "lkm_email") //设置该属性和数据库中的哪一个字段对应 private String lkmEmail; @Column(name = "lkm_qq") //设置该属性和数据库中的哪一个字段对应 private String lkmQq; @Column(name = "lkm_mobile") //设置该属性和数据库中的哪一个字段对应 private String lkmMobile; @Column(name = "lkm_memo") //设置该属性和数据库中的哪一个字段对应 private String lkmMemo; @Column(name = "lkm_position") //设置该属性和数据库中的哪一个字段对应 private String lkmPosition; @ManyToOne(targetEntity=Customer.class) @JoinColumn(name="lkm_cust_id",referencedColumnName="cust_id") private Customer customer; public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public Long getLkmId() { return lkmId; } public void setLkmId(Long lkmId) { this.lkmId = lkmId; } public Character getLkmGender() { return lkmGender; } public void setLkmGender(Character lkmGender) { this.lkmGender = lkmGender; } public String getLkmName() { return lkmName; } public void setLkmName(String lkmName) { this.lkmName = lkmName; } public String getLkmPhone() { return lkmPhone; } public void setLkmPhone(String lkmPhone) { this.lkmPhone = lkmPhone; } public String getLkmEmail() { return lkmEmail; } public void setLkmEmail(String lkmEmail) { this.lkmEmail = lkmEmail; } public String getLkmQq() { return lkmQq; } public void setLkmQq(String lkmQq) { this.lkmQq = lkmQq; } public String getLkmMobile() { return lkmMobile; } public void setLkmMobile(String lkmMobile) { this.lkmMobile = lkmMobile; } public String getLkmMemo() { return lkmMemo; } public void setLkmMemo(String lkmMemo) { this.lkmMemo = lkmMemo; } public String getLkmPosition() { return lkmPosition; } public void setLkmPosition(String lkmPosition) { this.lkmPosition = lkmPosition; } }
package com.tuling.cloud.study.entity; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column private String username; @Column private String name; @Column private Integer age; @Column private BigDecimal balance; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Integer getAge() { return this.age; } public void setAge(Integer age) { this.age = age; } public BigDecimal getBalance() { return this.balance; } public void setBalance(BigDecimal balance) { this.balance = balance; } }
3.2:创建repository接口对象
package com.tuling.cloud.study.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import com.tuling.cloud.study.entity.Customer; /* * 符合SpringDatajpa的dao层接口规范 *JpaRepository<操作的实体类类型,实体类中主键属性的类型> *封装了基本的CRUD操作 JpaSpecificationExecutor<操作的实体类类型> *封装了复杂查询操作(分页) * */ @Repository public interface CustomerDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> { //@Query 使用jpql的方式查询。?1代表参数的占位符,其中1对应方法中的参数索引 @Query(value="from Customer where custName = ?1") public Customer findCustomer(String custName); @Query(value="update Customer set custName = ?1 where custId = ?2") @Modifying public void updateCustomer(String custName,Long custId); /** * nativeQuery : 使用本地sql的方式查询 */ @Query(value="select * from cst_customer",nativeQuery=true) public List<Object[]> findSql(); @Query(value = "select * from cst_customer where cust_name like ?1",nativeQuery = true) public List<Object []> findSql2(String name); //方法命名方式查询(根据客户名称查询客户) public Customer findByCustName(String custName); public List<Customer> findByCustNameLike(String custName); public List<Customer> findByCustNameLikeAndCusIndustry(String custName,String cusIndustry); }
package com.tuling.cloud.study.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import com.tuling.cloud.study.entity.LinkMan; /* * 符合SpringDatajpa的dao层接口规范 *JpaRepository<操作的实体类类型,实体类中主键属性的类型> *封装了基本的CRUD操作 JpaSpecificationExecutor<操作的实体类类型> *封装了复杂查询操作(分页) * */ @Repository public interface LinnkManDao extends JpaRepository<LinkMan,Long>, JpaSpecificationExecutor<LinkMan> { }
package com.tuling.cloud.study.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.tuling.cloud.study.entity.User; @Repository public interface UserRepository extends JpaRepository<User, Long> { }
特别需要注意的是实体类和接口一定要被spring启动类的包扫描注解扫描到,spring boot默认扫描启动类的包及其子包目录,并且要使用@Repository加入到容器中,启动类的包目录为com.tuling.cloud.study,所有我们的接口类一定要在改包目录或者子包目录下
4、操作类
package com.tuling.cloud.study.controller; import java.util.Random; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.serviceregistry.Registration; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.tuling.cloud.study.entity.Customer; import com.tuling.cloud.study.entity.User; import com.tuling.cloud.study.repository.CustomerDao; import com.tuling.cloud.study.repository.UserRepository; @RestController public class UserController { private final Logger logger = Logger.getLogger(getClass()); @Autowired private UserRepository userRepository; @Autowired private Registration registration; @Autowired private CustomerDao customerDao; /* @GetMapping("/{id}") public User findById(@PathVariable Long id) throws Exception { logger.info("用户中心接口:查询用户"+ id +"信息"); if(id == 10){ throw new NullPointerException(); } Thread.sleep(3000); User findOne = userRepository.findOne(id); System.out.println("usernana is :"+findOne.getName()); return findOne; }*/ @GetMapping("/{id}") public User findById2(@PathVariable Long id) throws Exception { logger.info("用户中心接口:查询用户"+ id +"信息"); if(id == 10){ throw new NullPointerException(); } Thread.sleep(3000); Customer findOne = customerDao.findOne((long) 2);; System.out.println("usernana is :"+findOne.getCustName()); User user = new User(); user.setAge(100); user.setName(findOne.getCustName()); user.setUsername(findOne.toString()); return user; } @GetMapping("/getIpAndPort") public String findById() { return registration.getHost() + ":" + registration.getPort(); } @RequestMapping(value = "/aa", method = RequestMethod.GET) public String aa(){ return "aaaaaaa"; } }
5.项目的启动类
package com.tuling.cloud.study; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @EnableDiscoveryClient @SpringBootApplication public class ProviderUserApplication { public static void main(String[] args) { SpringApplication.run(ProviderUserApplication.class, args); } }
jpa其他的操作:
import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.stream.Collector; import java.util.stream.Collectors; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.sql.DataSource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Order; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.Query; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import com.atguigu.springdata.Customer; import com.atguigu.springdata.CustomerDao; import com.itcast.utils.JpaUtils; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:applicationContext.xml") public class SpringDataTest { @Autowired private CustomerDao customerDao; @Test public void testFind() { com.atguigu.springdata.Customer customer = customerDao.findOne((long) 2); System.out.println(customer.toString()); } /** * 保存客户:调用save(obj)方法 */ @Test public void testSave() { Customer c = new Customer(); c.setCustName("传智播客"); customerDao.save(c); } /** * 修改客户:调用save(obj)方法 * 对于save方法的解释:如果执行此方法是对象中存在id属性,即为更新操作会先根据id查询,再更新 * 如果执行此方法中对象中不存在id属性,即为保存操作 * */ @Test public void testUpdate() { //根据id查询id为1的客户 Customer customer = customerDao.findOne(1l); //修改客户名称 customer.setCustName("传智播客顺义校区"); //更新 customerDao.save(customer); } @Test public void testCount() { long count = customerDao.count(); System.out.println(count); } @Test public void testExits() { boolean exists = customerDao.exists((long) 2); System.out.println(exists); } @Test @Transactional public void testGetOne() { Customer one = customerDao.getOne((long) 2); System.out.println(one); } @Test @Transactional @Rollback(value=false) public void testupdateCustomer() { customerDao.updateCustomer("我是可不2222", (long) 2); } @Test public void testfindSql() { List<Object[]> datas = customerDao.findSql(); for(Object[] data:datas){ System.out.println(Arrays.toString(data)); } } //测试sql查询 @Test public void testFindSql() { List<Object[]> list = customerDao.findSql2("迅腾软件%");//模糊查询 for(Object[] obj: list){ System.out.println(Arrays.toString(obj)); } } @Test public void testFindSql22() { List<Customer> customers = customerDao.findByCustNameLikeAndCusIndustry("3333%","明星"); for(Customer customer:customers){ System.out.println(customer.toString()); } } @Test public void testFindSql223333() { Specification<Customer> spec = new Specification<Customer>() { public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) { // TODO Auto-generated method stub Path<Object> custName = root.get("custName"); Predicate predicate = cb.equal(custName, "3333"); return predicate; } }; Customer customer = customerDao.findOne(spec); System.out.println(customer.toString()); } @Test public void testFindSql223333222() { Specification<Customer> spec = new Specification<Customer>() { public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) { // TODO Auto-generated method stub Path<Object> custName = root.get("custName"); Path<Object> cusIndustry = root.get("cusIndustry"); Predicate predicate1 = cb.equal(custName, "3333"); Predicate predicate2 = cb.equal(cusIndustry, "2222"); Predicate predicate3 = cb.and(predicate1,predicate2); return predicate3; } }; Customer customer = customerDao.findOne(spec); System.out.println(customer.toString()); } @Test public void testFindSql223333222wwww() { Specification<Customer> spec = new Specification<Customer>() { public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) { // TODO Auto-generated method stub Path<Object> custName = root.get("custName"); Predicate predicate = cb.like(custName.as(String.class), "33%"); return predicate; } }; List<Customer> customer = customerDao.findAll(spec); System.out.println(customer.toString()); } @Test public void testFindSql223333222wwwwww() { Specification<Customer> spec = new Specification<Customer>() { public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) { // TODO Auto-generated method stub Path<Object> custName = root.get("custName"); Predicate predicate = cb.like(custName.as(String.class), "33%"); return predicate; } }; Sort sort = new Sort(Sort.Direction.ASC,"custId"); List<Customer> customer = customerDao.findAll(spec,sort); System.out.println(customer.toString()); } /** * 目标: 实现带查询条件的分页. id > 5 的条件 * * 调用 JpaSpecificationExecutor 的 Page<T> findAll(Specification<T> spec, Pageable pageable); * Specification: 封装了 JPA Criteria 查询的查询条件 * Pageable: 封装了请求分页的信息: 例如 pageNo, pageSize, Sort */ @Test public void testJpaSpecificationExecutorss(){ int pageNo = 3 - 1; int pageSize = 5; Sort sort = new Sort(Sort.Direction.ASC,"custId"); //封装分页的信息 PageRequest pageable = new PageRequest(pageNo, pageSize,sort); Specification<Customer> spec = new Specification<Customer>() { public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) { // TODO Auto-generated method stub Path<Object> custName = root.get("custName"); Predicate predicate = cb.like(custName.as(String.class), "33%"); return predicate; } }; Page<Customer> page = customerDao.findAll(spec, pageable); System.out.println("总记录数: " + page.getTotalElements()); System.out.println("当前第几页: " + (page.getNumber() + 1)); System.out.println("总页数: " + page.getTotalPages()); System.out.println("当前页面的 List: " + page.getContent()); List<Customer> content = page.getContent(); System.out.println("当前页面的记录数: " + page.getNumberOfElements()); /*List<Person> collect = page.getContent().stream().map(stat->(Person)stat).collect(Collectors.toList()); System.out.println("当前页面的 List1: " + collect);*/ } }
import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.stream.Collector; import java.util.stream.Collectors; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.sql.DataSource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Order; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.Query; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import com.atguigu.springdata.Customer; import com.atguigu.springdata.CustomerDao; import com.atguigu.springdata.LinkMan; import com.atguigu.springdata.LinnkManDao; import com.itcast.utils.JpaUtils; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:applicationContext.xml") public class oneToManyTest { @Autowired private CustomerDao customerDao; @Autowired private LinnkManDao linnkManDao; @Test @Transactional @Rollback(value=false) public void save(){ Customer customer = new Customer(); customer.setCustName("百度"); LinkMan linkMan = new LinkMan(); linkMan.setLkmName("小明"); linkMan.setCustomer(customer); customerDao.save(customer); linnkManDao.save(linkMan); } }
posted on 2020-01-04 11:12 luzhouxiaoshuai 阅读(492) 评论(0) 编辑 收藏 举报