spring data jpa 多對一聯表查詢

TurkeyJ發表於2019-03-16

public class Product {
@Id
@GeneratedValue
private Long id;
private String name;
private Double price;
private String standerd;
private String code;
private String srcPath;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = “user_id”)
private User user;

public User getUser() {
    return user;
}
public void setUser(User user) {
    this.user = user;
}

Repository :

public interface ProductRepository extends JpaRepository<Product,Long> {
@Query("select p from Product p join p.user u where u.id=?1 ")
List findByUserId(@Param(“userId”) Long userId);
}

controller:

@PostMapping("/findProductByUserName")
public List findProductByName(@RequestParam(“name”)String name){
User user=userService.findByProperty(name);
List productList=productService.findByUserId(user.getId());
return productList;

相關文章