【发布时间】:2020-03-29 17:08:11
【问题描述】:
我有使用 JPA/Hibernate、MySQL 的 spring boot 项目。我有三个具有多对多关系的道类。
Poko 类看起来像这样
产品
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false, columnDefinition = "integer")
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "price")
private Double price;
@ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(
name = "product_extra",
joinColumns = @JoinColumn(name="product_id"),
inverseJoinColumns = @JoinColumn(name="extra_id")
)
private List<Extra> extras = new ArrayList<>();
//constructor getters and setters
}
产品附加
@Entity
@Table(name = "product_extra")
public class ProductExtra {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false, columnDefinition = "integer")
private Integer id;
@Column(name = "product_id")
private Integer productId;
@Column(name = "extra_id")
private Integer extraId;
//constructor getters and setter
}
额外
@Entity
@Table(name = "extra")
public class Extra {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false, columnDefinition = "integer")
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "price")
private Double price;
@ManyToMany(mappedBy = "extras")
private List<Product> products = new ArrayList<>();
//constructor getters and setters
}
带有查询的额外存储库
public interface ExtraRepository extends JpaRepository<Extra, Integer> {
@Query("SELECT e.id, e.name, e.price FROM Extra e INNER JOIN ProductExtra pe ON e.id = pe.extraId WHERE pe.productId = ?1")
List<Extra> findExtraById(Integer productId);
}
我的控制器中的映射
@GetMapping("/product/{productId}")
public List<Extra>getExtraById(@PathVariable("productId") final Integer productId){
return extraRepository.findExtraById(productId);
}
我正在尝试进行多对多查询以选择每个产品中的附加功能,但是我收到此错误Failed to convert from type [java.lang.Object[]] to type [@org.springframework.data.jpa.repository.Query 错误消息令人惊讶地还包含我想要的结果。不知道哪里做错了
【问题讨论】:
标签: mysql hibernate spring-boot jpa