SpringBoot整合JPA

依赖

<dependencies>
  
  <dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-jdbcartifactId>
  dependency>
  <dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-data-jpaartifactId>
  dependency>
  <dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-webartifactId>
  dependency>
  <dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-devtoolsartifactId>
    <scope>runtimescope>
    <optional>trueoptional>
  dependency>
  
  <dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
    <scope>runtimescope>
  dependency>
  
  <dependency>
    <groupId>org.projectlombokgroupId>
    <artifactId>lombokartifactId>
    <optional>trueoptional>
  dependency>
  
  <dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-testartifactId>
    <scope>testscope>
  dependency>
    dependencies>

配置文件

server:
  port: 8080
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://xxxx:3306/logistics?serverTimezone=UTC
    password: root
    username: root
  jpa:
#    database: MYSQL
    show-sql: true
    hibernate:
      ddl-auto: update

编写实体类

@Data //lombok
@Entity //声明这是一个实体类
@Table(name = "`order`") //与数据库表对应起来
@Accessors(chain = true) //链式调用(可有可无)
public class Order {
    @Id // 主键id
    @GeneratedValue(strategy = GenerationType.IDENTITY) //主键类型这是数据库自增
    private Integer id;

    private String orderNumber;

    private Integer skuId;

    private String userName;
}

对应的Dao映射

public interface OrderDao extends JpaRepository<Order,Integer>,JpaSpecificationExecutor<Order>{
// JpaRepository<实体类,主键类型> 基本的CRUD
// JpaSpecificationExecutor 分页多条件查询 排序等功能
}

基本测试使用

分页查询

public List<Order> listPage() {
        //分页对象
        PageRequest of = PageRequest.of(0, 10);
        //构建查询条件
        Page<Order> orders = orderDao.findAll(new Specification<Order>() {
            /**
             *
             * @param root 实体类
             * @param query 查询对象
             * @param criteriaBuilder 条件构建
             * @return
             */
            @Override
            public Predicate toPredicate(Root<Order> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                // between root.get("skuId").as(Integer.class)->获取skuId 字段
                Predicate skuIda = criteriaBuilder.between(root.get("skuId").as(Integer.class), 0, 10);
                // 排序
                javax.persistence.criteria.Order id = criteriaBuilder.desc(root.get("id").as(Integer.class));
                //将条件放入到Wher中
                query.where(skuIda);
                //可以指定多个排序
                query.orderBy(id);
                //给定查询条件
                return query.getRestriction();
            }
        }, of);
        List<Order> content = orders.getContent();
        return content;
    }
  • 效果![image.png](https://img-blog.csdnimg.cn/img_convert/2edcdc8e478c1f99b59c382a93922f1c.png#clientId=ub8e45ee4-2cc5-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=220&id=u09dd9cf8&margin=[object Object]&name=image.png&originHeight=220&originWidth=1867&originalType=binary&ratio=1&rotation=0&showTitle=false&size=28653&status=done&style=none&taskId=uf47902d6-6894-4aae-9784-757c498cf8b&title=&width=1867)

public void adds() {
        List<Order> orders = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            Order order = new Order().setOrderNumber(String.valueOf(i))
                    .setSkuId(i)
                    .setUserName(String.valueOf(i));
            orders.add(order);
        }
        orderDao.saveAll(orders);

    }

@Test
void deleteOrder(){
    //如果数据中没有id=10的记录则会抛出异常
    orderDao.deleteById(10);
}

![image.png](https://img-blog.csdnimg.cn/img_convert/8829b7335a8ff4aba0c9b14fc3391c23.png#clientId=ub8e45ee4-2cc5-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=490&id=u9bae3db2&margin=[object Object]&name=image.png&originHeight=490&originWidth=1112&originalType=binary&ratio=1&rotation=0&showTitle=false&size=147934&status=done&style=none&taskId=u9c83e045-8507-43c7-bdda-8686692b51c&title=&width=1112)

  • 处理办法
@Test
void deleteOrder(){
    if(orderDao.existsById(10)) {
        orderDao.deleteById(10);
    }
}
  • 或者在dao层写出方法,加上@Transactional
public interface OrderDao extends JpaRepository<Order,Integer>,JpaSpecificationExecutor<Order>{

    @Transactional
    void deleteOrdersByIdIn(List<Integer> ids);

}

@Test
void deleteTest(){
    List<Integer> ids = new ArrayList<>();
    ids.add(59);
    ids.add(60);
    orderDao.deleteOrdersByIdIn(ids);
}

![image.png](https://img-blog.csdnimg.cn/img_convert/876e6142022b3e270f8f0864f63268fd.png#clientId=u6f567b39-f53f-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=309&id=u9a62c876&margin=[object Object]&name=image.png&originHeight=309&originWidth=1729&originalType=binary&ratio=1&rotation=0&showTitle=false&size=24779&status=done&style=none&taskId=u2b76ee06-618b-4242-aa3c-d98b10b55ed&title=&width=1729)

@Test
void updateTest(){
    Order order = new Order().setId(61)
            .setUserName("阿巴阿巴")
            .setOrderNumber("61")
            .setSkuId(61);
    orderDao.saveAndFlush(order);

}

自定义SQL

  • 查询
public interface OrderDao extends JpaRepository<Order,Integer>,JpaSpecificationExecutor<Order>{

    @Query(value = "select * from `order` where sku_Id > ?1",nativeQuery = true)
    List<Order> getOrderBySkuId(Integer skuId);
}
 @Test
void getSkuId(){
    List<Order> orderBySkuId = orderDao.getOrderBySkuId(17);
    System.out.println(orderBySkuId);
}

![image.png](https://img-blog.csdnimg.cn/img_convert/ff5b67f7dcdbb401476a3647d4219e8f.png#clientId=u6f567b39-f53f-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=143&id=u96d9814f&margin=[object Object]&name=image.png&originHeight=143&originWidth=1481&originalType=binary&ratio=1&rotation=0&showTitle=false&size=14164&status=done&style=none&taskId=u3b9e61c6-5717-4aec-8362-2a41acb6abf&title=&width=1481)

  • 修改
public interface OrderDao extends JpaRepository<Order,Integer>,JpaSpecificationExecutor<Order>{
    @Transactional
    @Modifying
    @Query(value = "delete  from `order` where sku_id = ?1 and user_name = ?1" ,nativeQuery = true)
    void deleteOrderBySkuIdAndUserName(Integer skuId,String userName);
}
@Test
void deleteBySkuIdAndUserName(){
    orderDao.deleteOrderBySkuIdAndUserName(7,"7");
}

![image.png](https://img-blog.csdnimg.cn/img_convert/e359c663c5b203609d262048d7119521.png#clientId=u6f567b39-f53f-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=304&id=u33511171&margin=[object Object]&name=image.png&originHeight=304&originWidth=1905&originalType=binary&ratio=1&rotation=0&showTitle=false&size=27552&status=done&style=none&taskId=u0fcce61e-5b75-4b61-9871-607ab7e6b5e&title=&width=1905)

我的评价:不如Mybatis-plus

你可能感兴趣的:(spring,boot,jpa)