我有两个实体类。
order.Java
@Entity
@Table(name = "order_table")
public class Order implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "order_id", referencedColumnName = "id", nullable = false, insertable=false, updatable=false)
private Set<Item> items;
// getters & setters & toString
item.Java
@Entity
@Table(name = "item")
public class Item implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@Column(name = "order_id", nullable = false)
private Long orderId;
// getters & setters && toString
我创建了一个测试类是这样的:
@Test
public void createOrderWithItems() {
Item item = new Item();
item.setName("Iron Man");
Order order = new Order();
order.setName("Toy");
order.getItems().add(item);
Order created = service.createOrder(order);
Order orderById = service.getOrderById(order.getId());
System.out.println("Created Order: " + orderById);
Item itemById = service.getItemById(item.getId());
System.out.println("Created item: " + itemById);
Assert.notNull(created.getId(), "Order ID is Null");
}
测试是绿色的,但如果你检查输出,你会看到在orderId
类Item
字段为空。
Created Order: Order{id=1, name='Toy', items=[Item{id=2, name='Iron Man', orderId=null}]}
Created item: Item{id=2, name='Iron Man', orderId=null}
JPA是否不更新自动分贝此列?这是列是多余的?如果是这样,我怎么能检索测试代码这一信息?
您需要设置的orderId明确。
item.setOrderId(order.getId());
order.getItems().add(item);
您可以在addItem(Item item)
类中创建一个方法Order
并在其中隐藏这个逻辑。
层叠将创建数据库的条目,但它不会初始化场。 JPA注释只是指示JPA提供商如何实体和表之间进行映射。
此外,检查您的注解。 @JoinColumn
应该在拥有该关系的实体使用(相应的表含有列作为外键)。检查顶部答案这个问题进行详细的解释:What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association