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

杰伊:

简短摘要:我得到了一个具有嵌入式密钥(id,制造商)的Product实体。我通过休息与制造商的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;
    }

更新:我遵循以下stackoverflow帖子,我将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:似乎没有填充产品的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?

杰伊:

我最初的问题是:

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时,可能是与休眠有关bug(或此bug)。

无论哪种方式,解决此问题和解决问题的方法都是将id列初始化为一个value:

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的休眠验证,并允许它随后将序列值映射到它。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章