无法确定 Java 类型“java.util.Map<java.lang.String, java.util.List<java.lang.String>>”的推荐 JdbcType

问题描述 投票:0回答:1

我遇到了这个错误:

Caused by: org.hibernate.type.descriptor.java.spi.JdbcTypeRecommendationException: Could not determine recommended JdbcType for Java type 'java.util.Map<java.lang.String, java.util.List<java.lang.String>>' 

如何将下面的 MAP 映射到 Hibernate 似乎是一个错误

private Map<String, List<ProductDetails>> productCatalogue;

这是类别(键)映射到产品列表(值)的映射。

请参阅下面的公司实体中地图的用法:

@Entity 
@Table(name = "company")
public class Company {
    
    @Id
  @GeneratedValue(strategy=GenerationType.AUTO) 
  private Long company_id; 

  private String companyName;

  private Map<String, List<ProductDetails>> productCatalogue;


public void addProductToCatalogue(ProductDetails product) {
        // Get the product category
        String category = product.getCategory();

        // Check if the category is already in the map
        if (!productCatalogue.containsKey(category)) {
            productCatalogue.put(category, new ArrayList<>());
        }

        // Add the product to the corresponding category in the map
        productCatalogue.get(category).add(product);
    }    

下面是我的 ProductDetails 实体的样子:

@Entity 
@Table(name = "product")
public class ProductDetails {
  
   @Id
  @GeneratedValue(strategy=GenerationType.AUTO) 
    
  private Long product_id;  
  private String category;
  private String name;
  
  // Many-to-One relationship with Company
    @ManyToOne
    @JoinColumn(name = "company_id")
    private Company company;
 

我尝试使用 @ElementCollection 的注释。但没有解决:

@ElementCollection
   @CollectionTable(name = "product_catalogue", joinColumns = @JoinColumn(name = "company_id"))
   @MapKeyColumn(name = "category")
   @Column(name = "product_id")
  private Map<String, List<ProductDetails>> productCatalogue;
java mysql spring-boot hibernate jpa
1个回答
0
投票

我认为你可以做这样的事情。将该字段标记为瞬态,然后在加载实体后填充它。

@Entity
@Table(name = "company")
public class Company {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long company_id;

    private String companyName;

    @OneToMany
    private List<ProductDetails> productDetails;

    @Transient
    private Map<String, List<ProductDetails>> productCatalogue;

    public Map<String, List<ProductDetails>> getProductCatalogue() {
        return productCatalogue;
    }

    @PostLoad
    public void addProductToCatalogue(List<ProductDetails> productDetailList) {

        for (ProductDetails product : productDetailList) {
            // Get the product category
            String category = product.getCategory();

            // Check if the category is already in the map
            if (!productCatalogue.containsKey(category)) {
                productCatalogue.put(category, new ArrayList<>());
            }
            // Add the product to the corresponding category in the map
            productCatalogue.get(category).add(product);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.