一、jpa自定义sql语句查询:
1、在OrderInfoRepository加上方法:
/**
* 删除某个userId的订单
* @param userId
* @return
*/
@Modifying
@Query("DELETE FROM OrderInfo WHERE userId = ?1")
void deleteOrderInfoBy(Integer userId);
2、单元测试:
@Test
@Transactional
public void deleteOrderInfoBy() {
repository.deleteOrderInfoBy(1);
}
3、执行测试,结果:
4、自定义sql语句时,需要注意的是涉及到数据改动和删除时,需要在接口方法上加@Modifying,同时需要在调用方法上加上事务注解@Transactional,也可以直接加在repository接口方法上。
二、jpa多表查询。
第一种方式,接口接收参数
1、先定义一个接收参数的接口:
package com.cobra.jpademo.dto;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.math.BigDecimal;
/**
* @Author: Baron
* @Description:
* @Date: Created in 2019/3/10 0:13
*/
public interface OrderDetailDTO {
Integer getOrderId();
String getOrderDesc();
BigDecimal getOrderFee();
String getUsername();
String getEmail();
}
2、在repository(可随意,哪个都行)中,新建接口方法(sql语句里需要用AS指定列别名):
/**
* 根据userId查询订单详情(包含用户信息)
* @param userId
* @return
*/
@Query("SELECT o.orderId AS orderId,o.orderDesc AS orderDesc,o.orderFee " +
"AS orderFee,u.username AS username,u.email AS email " +
"FROM OrderInfo o , UserInfo u " +
"WHERE o.userId=u.userId AND o.userId=?1")
List findOrderDetailDTOByUserId(Integer userId);
3、单元测试:
@Test
public void findOrderDetailDTOByUserId() {
List orderDetails = repository.findOrderDetailDTOByUserId(2);
for (OrderDetailDTO orderDetail:orderDetails) {
log.info("orderDetail={}",orderDetail.getOrderId()+
orderDetail.getOrderDesc()+orderDetail.getOrderFee()+orderDetail.getUsername());
}
}
第二种方式:带有全参构造方法的类接收参数
1、定义一个接收数据的类
package com.cobra.jpademo.dto;
import lombok.Data;
import java.math.BigDecimal;
/**
* @Author: Baron
* @Description:
* @Date: Created in 2019/3/10 0:13
*/
@Data
public class OrderDetailDTO {
private Integer orderId;
private String orderDesc;
private BigDecimal orderFee;
private String username;
private String email;
public OrderDetailDTO() {
}
public OrderDetailDTO(Integer orderId, String orderDesc, BigDecimal orderFee, String username, String email) {
this.orderId = orderId;
this.orderDesc = orderDesc;
this.orderFee = orderFee;
this.username = username;
this.email = email;
}
}
2、在repository(可随意,哪个都行)中,新建接口方法(注意DTO类路径要写上):
/**
* 根据userId查询订单详情(包含用户信息)
* @param userId
* @return
*/
@Query("SELECT new com.cobra.jpademo.dto.OrderDetailDTO(o.orderId,o.orderDesc,o.orderFee,u.username,u.email) " +
"FROM OrderInfo o , UserInfo u " +
"WHERE o.userId=u.userId AND o.userId=?1")
List findOrderDetailDTOByUserId(Integer userId);
3、单元测试:
@Test
public void findOrderDetailDTOByUserId() {
List orderDetails = repository.findOrderDetailDTOByUserId(2);
log.info("orderDetails={}",orderDetails);
}