springboot集成jpa操作mybatis数据库
数据库如下
CREATE TABLE `jpa`.`Untitled` (
`cust_id` bigint() NOT NULL AUTO_INCREMENT,
`cust_address` varchar() CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`cust_industry` varchar() CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`cust_level` varchar() CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`cust_name` varchar() CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`cust_phone` varchar() CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`cust_source` varchar() CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
PRIMARY KEY (`cust_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
CREATE TABLE `jpa`.`Untitled` (
`lkm_id` bigint() NOT NULL AUTO_INCREMENT,
`lkm_email` varchar() CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`lkm_gender` char() CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`lkm_memo` varchar() CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`lkm_mobile` varchar() CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`lkm_name` varchar() CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`lkm_phone` varchar() CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`lkm_position` varchar() CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`lkm_qq` varchar() CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`lkm_cust_id` bigint() 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 = CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
CREATE TABLE `jpa`.`Untitled` (
`id` int() NOT NULL AUTO_INCREMENT,
`city` varchar() CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`province` varchar() CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
CREATE TABLE `jpa`.`Untitled` (
`id` int() NOT NULL AUTO_INCREMENT,
`birth` datetime() DEFAULT NULL,
`email` varchar() CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`last_name` varchar() CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`address_id` int() 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 = 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); } }
springboot集成jpa操作mybatis数据库的更多相关文章
- springboot集成jpa,在postgresql数据库中创建主键自增表
依赖文件 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http:/ ...
- Spring同时集成JPA与Mybatis
@ 目录 ORM Spring ORM Spring ORM 同时集成JPA与Mybatis 一.创建一个SpringBoot项目 二.建立用户信息登记表 三.Web应用项目集成mysql 四.添加S ...
- Spring Data JPA系列2:SpringBoot集成JPA详细教程,快速在项目中熟练使用JPA
大家好,又见面了. 这是Spring Data JPA系列的第2篇,在上一篇<Spring Data JPA系列1:JDBC.ORM.JPA.Spring Data JPA,傻傻分不清楚?给你个 ...
- 用SpringBoot+MySql+JPA实现对数据库的增删改查和分页
使用SpringBoot+Mysql+JPA实现对数据库的增删改查和分页 JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述 ...
- springboot集成redis(mybatis、分布式session)
安装Redis请参考:<CentOS快速安装Redis> 一.springboot集成redis并实现DB与缓存同步 1.添加redis及数据库相关依赖(pom.xml) <depe ...
- springboot集成下,mybatis的mapper代理对象究竟是如何生成的
前言 开心一刻 中韩两学生辩论. 中:端午节是属于谁的? 韩:韩国人! 中:汉字是谁发明的? 韩:韩国人! 中:中医是属于谁的? 韩:韩国人! 中:那中国人到底发明过什么? 韩:韩国人! 前情回顾 M ...
- springboot 集成 jpa/hibernate
pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...
- springboot集成liquibase,h2数据库
Liquibase是一个用于跟踪.管理和应用数据库变化的开源的数据库重构工具.它将所有数据库的变化(包括结构和数据)都保存在XML文件中,便于版本控制. Liquibase具备如下特性:* 不依赖于特 ...
- springboot支付项目之springboot集成jpa
springboot集成spring-jpa 本文主要内容: 1:spring boot怎么集成spring-jpa以及第一个jpa查询示例 如jpa几个常用注解.lombok注解使用 2:怎么设置i ...
随机推荐
- 应小姐姐要求,整理常用Git操作命令,她都学会了,你确定不收藏
前言 因为个人原因,转化了部门之后已经很久没有接触过开发层级的东西了,好多东西基本都忘记了,但是新的部门有时候会用到相应的研发部的代码和文档手册,所以耳边就充斥这一句话 这个为什么下载不了?这个为什么 ...
- Rocket - subsystem - CrossingWrapper
https://mp.weixin.qq.com/s/3-MfNJDCIgOBqUbf4fuerQ 简单介绍CrossingWrapper的实现. 1. CrossesToOnlyOneClockDo ...
- Rocket - tilelink - CacheCork
https://mp.weixin.qq.com/s/QsL1Bfb0JsOaxWW_muhg_Q 简单介绍CacheCork的实现. 1. 基本介绍 Cache的塞子,下游没有 ...
- for循环的嵌套 函数方法
1.双层for循环:外层循环控制行,内行循环控制列 for循环嵌套例子 用五角星组成一个矩形 // 99乘法表 // for(var i = 1 ;i <= 9 ; i++){ // f ...
- java继承会犯的小错误
注意事项:阅读本文前应该先了解java的继承.本文定位为已经继承基础知识. 一:试图覆盖私有方法 先上代码 public class Father { private void print() { S ...
- org.openqa.selenium.WebDriverException: It is impossible to create a new session because 'createSession' which takes HttpClient, InputStream and long was not found or it is not accessible 异常
检查项目配置的jdk版本是否过低,修改一下配置就解决了.如果是jdk版本过低的就升级一下jdk.
- 温故知新-多线程-Cache Line存在验证
文章目录 简述 缓存行Cache Line 验证CacehLine存在? 参考 你的鼓励也是我创作的动力 Posted by 微博@Yangsc_o 原创文章,版权声明:自由转载-非商用-非衍生-保持 ...
- PAT 1038 Recover the Smallest Number (30分) string巧排序
题目 Given a collection of number segments, you are supposed to recover the smallest number from them. ...
- javascript 面向对象学习(二)——原型与继承
什么是原型? 首先我们创建一个简单的空对象,再把它打印出来 var example = {} console.log(example) 结果如下: { __proto__: { constructor ...
- synchronized 和 java.util.concurrent.locks.Lock 的异同 ?
主要相同点:Lock 能完成 synchronized 所实现的所有功能 主要不同点:Lock 有比synchronized 更精确的线程语义和更好的性能. synchronized 会自动释放锁,而 ...