如何将@JsonIdentityInfo与复合PK一起使用?

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

如果我的课程只有一个

@Id
字段,我可以像这样使用
@JsonIdentityInfo

@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
class Example {

    @Id
    int id;
    // getter setter
}

但是如果我有一个综合PK类:

@Entity
@IdClass(value = PointID.class)
public class Point {

    @Id
    private int x;
    @Id
    private int y;
}

@SuppressWarnings("serial")
class PointID  implements Serializable {
    int x, y;
}

如何使用注释?在上面的例子中,用法会是这样的

Point p = new Point(1,1);
object1.setPoint(p);
object2.setPoint(p);
bigObject.add(object1, object2);

当我序列化时

bigObject
我不想重复点数据,而是像第一个示例一样使用它的ID。

java jpa jackson
3个回答
4
投票

我搜索了Jackson文档和源代码,没有找到对由多个属性组成的object-id的支持。

所以我给你的建议是在 getter 方法中创建这样的组合键:

@Entity
@IdClass(value = PointID.class)
public class Point {

    @Id
    private int x;
    @Id
    private int y;

    @JsonIdentityInfo(
        generator = ObjectIdGenerators.PropertyGenerator.class,
        property = "pk")
    public String getPk() {
        return x + "->" + y;
    }

    @JsonIgnore
    public int getX() {
        return x + "->" + y;
    }

    // @JsonIgnore on all individual properties that make pk
}

2
投票

根据我的尝试和网上研究,

@JsonIdentityInfo
似乎不适用于复合PK。


0
投票

试试这个

主要实体:

@Entity
@Table(name = "INVOICE_ENTRIES")
public class InvoiceEntry {

  @EmbeddedId
  private InvoiceEntryPK id;

  @ManyToOne
  @JoinColumn(name = "A_COLUMN")
  private String aProperty;
  ...
  Getters and setters
  ...
}

PK实体:

@Embeddable
public class InvoiceEntryPK {

  @ManyToOne
  @JoinColumn(name = "CUSTOMER")
  @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
  property = "id",
  resolver = MyIdResolver.class,
  scope = Customer.class)
  private Customer customer;

  @ManyToOne
  @JoinColumn(name = "PRODUCT")
  @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
  property = "id",
  resolver = MyIdResolver.class,
  scope = Product.class)
  private Product product;
  ...
  Getters and setters
  ...
}

现在,MyIdResolver 类:

public class MyIdResolver implements ObjectIdResolver {
  private EntityManager em;
  public MyIdResolver(final EntityManager em) {
    this.em = em;
  }
  @Override
  public void bindItem(IdKey id, Object pojo) {
  }
  @Override
  public Object resolveId(IdKey id) {
    return this.em.find(id.scope, id.key);
  }
  @Override
  public ObjectIdResolver newForDeserialization(Object context) {
    return this;
  }
  @Override
  public boolean canUseFor(ObjectIdResolver resolverType) {
    return false;
  }
}

现在,您可以反序列化此 JSON:

{
  id: {
    customer: 72,
    product: 105
  },
  aProperty: "Some text..."
}
© www.soinside.com 2019 - 2024. All rights reserved.