我在帖子中创建了一个OneToOne关系:https://stackoverflow.com/a/536102/494659
同样,我们有两个实体:Invoice
& InvoiceSequence
基本上是它的序列。
@Entity
@Table(name = "invoices", indexes = {...})
@JsonIgnoreProperties(ignoreUnknown = true)
public class Invoice implements Serializable {
private static final long serialVersionUID = 1L;
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Id
private String id;
@OneToOne(cascade = CascadeType.ALL, mappedBy = "invoice")
private InvoiceSequence invoiceSequence;
...
}
和InvoiceSequence实体:
@Entity
public class InvoiceSequence {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long seqId;
@OneToOne
private Invoice invoice;
@Override
public String toString() {
return new ToStringBuilder(this)
.append("seqId", seqId)
.toString();
}
}
但是当我们保存Invoice时,InvoiceSequence保存为null。 例如,在我的单元测试中;
Invoice invoice = new Invoice();
invoice.setFleetId("F0001");
invoice.setInvoicesStatus(InvoicesStatus.PENDING);
invoice.setPricingId("1V1");
invoice.setInvoiceDate(Date.from(toInstant));
invoice.setTripId("000011111");
invoice.setServiceId("001111");
invoice.setUserId("1");
invoice.setAmount(new BigDecimal("56"));
invoiceService.save(invoice);
当我调试并查看(在内存中,H2)db时,我看到invoiceSequence为null。
问题非常简单:当我们插入新的Invoice 时,如何确保我们在long值中增加了InvoiceSequence?
但我不能让它发挥作用,任何想法我做错了什么?
由于
答案 0 :(得分:4)
这似乎是实现序列的错误方法。你为什么不在Invoice
中有另一个字段,例如sequence
,并使用以下内容生成它:
Multiple Hibernate sequence generators for one entity with PostgreSQL
此外,如果您确实希望按照建议的方式执行此操作,则需要手动创建InvoiceSequence
,然后在保存之前将其设置为Invoice
。您还需要将Invoice
设置为InvoiceSequence
,如下所述:
https://www.callicoder.com/hibernate-spring-boot-jpa-one-to-one-mapping-example/