繁体   English   中英

作为 DerivedIdentities 的一部分,通过 rest 调用在 json 中传递 fk

[英]Passing fk in json via rest call as part of DerivedIdentities

我有一个具有嵌入式密钥(id,制造商)的 Product 实体。 我正在通过 REST 使用制造商的 fk 调用产品实体:

{
    "name":"Chocolate",
    "register_date":"19/03/2020",
    "manufacturer_id": 52,
    "rating":"Amazing"
}

当我尝试将实体保存在控制器中时,出现以下错误

java.lang.IllegalArgumentException: Can not set com.dao.Manufacturer field com.dao.ProductId.manufacturer to java.lang.Long

产品 :

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@IdClass(ProductId.class)
@Entity
public class Product {

    @Id
    @SequenceGenerator(name = "product_id_seq", sequenceName = "product_id_seq", initialValue = 1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE,generator = "product_id_seq")
    private Long id;

    @ManyToOne(fetch=FetchType.LAZY)
    @Id
    private Manufacturer manufacturer;
    
    private String name;

    @JsonFormat(pattern = "dd/MM/YYYY")
    private Date register_date;


    @Enumerated(EnumType.ORDINAL)
    private Rating rating;

    public enum Rating {
        Amazing,Good_Value_For_Money,Bad
    }

Id 类:

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@AllArgsConstructor
@NoArgsConstructor
public class ProductId implements Serializable {

    private Long id;
    private Manufacturer manufacturer;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ProductId pId1 = (ProductId) o;
        if (id != pId1.id) return false;
        return manufacturer.getId() == pId1.manufacturer.getId();
    }

    @Override
    public int hashCode() {
        return id.hashCode()+manufacturer.getId().hashCode();
    }
}

我还创建了一个 DTO 对象,它将通过 api 传递给控制器​​:

@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor

public class ProductCreationDTO {


    private String name;
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/mm/yyyy")
    private Date register_date;
    private Long manufacturer_id;
    private Product.Rating rating;

}

生产厂家 :

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Manufacturer {

    @Id
    @SequenceGenerator(name = "manufacturer_id_seq", sequenceName = "manufacturer_id_seq", initialValue = 1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE,generator = "manufacturer_id_seq")
    private Long id;
    private String name;
    private String country;
    @OneToMany(mappedBy = "manufacturer",fetch = FetchType.LAZY)
    private List<Product> products;

在我的控制器中,我有以下两个功能:

    RestController
    @RequestMapping("/api")
    public class ProductController {
    
        @Autowired
        ProductService productService;
    
        @Autowired
        ManufacturerService manufacturerService;
    
    
        @RequestMapping(value = "/product/", method = RequestMethod.POST)
        public HttpStatus insertProduct(@RequestBody ProductCreationDTO pcd) {
            Product p = mapProductCreationDTOtoProduct(pcd);
            if(p.getManufacturer() == null)
                return HttpStatus.BAD_REQUEST;
            return productService.addProduct(p) ? HttpStatus.CREATED : HttpStatus.BAD_REQUEST;
        }
    
        private Product mapProductCreationDTOtoProduct(ProductCreationDTO pcd)
        {
            Product p = new Product();
            p.setName(pcd.getName());
            p.setRating(pcd.getRating());
            p.setRegister_date(pcd.getRegister_date());
            Optional<Manufacturer> m = manufacturerService.getManufacturer(pcd.getManufacturer_id());
            if (m.isPresent())
                p.setManufacturer(m.get());
            return p;
        }

the add method under the productService : 

    @Transactional
    public boolean addProduct(Product p)
    {
        return productRepository.save(p)!=null;
    }

更新

我关注了以下Stack Overflow 帖子 我将 ProductId 更改为:

public class ProductId implements Serializable {

    private Long id;
    private Long manufacturer;
....

在 Product 类中,我在 Manufacturer 上方添加了以下注释:

@Id
@ManyToOne(fetch=FetchType.LAZY)
@MapsId("manufacturer")
private Manufacturer manufacturer;

现在我收到以下错误:

org.hibernate.HibernateException: No part of a composite identifier may be null

更新 2

看起来 Product 的 id 没有填充,这就是它没有创建的原因。 我尝试在以下函数中设置 id 并成功插入产品:

private Product mapProductCreationDTOtoProduct(ProductCreationDTO pcd)
{
    Product p = new Product();
    p.setName(pcd.getName());
    p.setRating(pcd.getRating());
    p.setRegister_date(pcd.getRegister_date());
    Optional<Manufacturer> m = manufacturerService.getManufacturer(pcd.getManufacturer());
    if (m.isPresent())
        p.setManufacturer(m.get());
    p.setId((long) 1);   <-------------------------------------------
    return p;
}

所以现在悬而未决的问题是为什么没有填充 id ?

明显的错误是在Product实体中的name属性上添加了@id注释,而它应该在manufacturer属性上

我原来的问题是:

java.lang.IllegalArgumentException: Can not set com.dao.Manufacturer field com.dao.ProductId.manufacturer to java.lang.Long

我按照这篇文章解决了这个问题 底线是在我的 IdClass 中,复合对象的类型应该是他的 PK :

public class ProductId implements Serializable {

    private Long id; // matches name of @Id attribute
    private Long manufacturer; // name should match to @Id attribute and type of Manufacturer PK

虽然解决它后我面临一个新的:

org.hibernate.HibernateException: No part of a composite identifier may be null

可能是使用@Idclass 时与休眠相关的错误(或此错误)。

无论哪种方式,处理这个问题并解决它的方法是将 id 列初始化为一个值:

public class Product {

    @Id
    @SequenceGenerator(name = "product_id_seq", sequenceName = "product_id_seq")
    @GeneratedValue(strategy= GenerationType.SEQUENCE,generator = "product_id_seq")
    private Long id=-1L;

这将绕过 id 的休眠验证,并允许它随后将序列值映射到它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM