我有两张桌子
@Entity
@Table(name = "TAX_CATEGORY")
public class TaxCategory {
@Id
@GeneratedValue
@Column(name = "ID", nullable = false)
private long id;
@Column(name = "CATEGORY", nullable = false)
private String category;
@Column(name = "TAX", nullable = false)
private Double tax;
@Entity
@Table(name = "PRODUCT")
public class Product {
@Id
@GeneratedValue
@Column(name = "ID", nullable = false)
private long id;
@Column(name = "PRICE", nullable = false)
private Double price;
@Column(name = "NAME", nullable = false)
private String name;
@OneToOne
@JoinColumn(name = "TAX_CATEGORY_ID")
private TaxCategory taxCategory;
现在我想查询
"Select p.name, p.price, t.tax from Product p, TaxCategory t join p.taxCategory.id=t.id"
所以列表它会返回 ProductName ProductPrice Tax
但我无法从两个表中获取此数据。单表数据工作正常。
public interface CustomRepositoryCustom {
public void customMethod();
}
public interface CustomRepository
extends JpaRepository<Account, Long>, CustomRepositoryCustom { }
public class CustomRepositoryImpl implements CustomRepositoryCustom {
public void customMethod() {
Query nativeQuery = entityManager.createNativeQuery("Select p.name, p.price, t.tax from Product p, TaxCategory t join p.taxCategory.id=t.id");
return query.getResultList();
}
}
抛出异常,即对象不是托管bean。如果我创建自定义对象,那么它也会提供类似的问题。
答案 0 :(得分:0)
使用以下JPA查询获取两个表数据。这里使用jpa查询来获取产品。从product对象中,可以获得taxCategory。
public interface CustomRepository extends JpaRepository<Account, Long>, CustomRepositoryCustom {
Query("select product from Product as product join fetch product.taxCategory as taxCategory where taxCategory.id = :taxCategoryId")
public Product getProductByCategory(@Param Long taxCategoryId);
}
答案 1 :(得分:0)
您可以直接定义JPA方法,而不是查询方法,以根据类别ID查找产品。
@Repository
@RepositoryRestResource
public interface ICountryRepository extends JpaRepository<Product , Long > {
List<Product> findByTaxCategory_Id(@Param Long Id);
}