jpa外键使用基础保存,请用java代码示例
时间: 2024-01-06 18:06:46 浏览: 82
好的,以下是一个使用JPA进行基础保存并使用外键的Java代码示例:
```
@Entity
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "customer_id", nullable = false)
private Customer customer;
// other fields and methods
}
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// other fields and methods
}
// code to save an Order with a Customer
Customer customer = new Customer();
// set customer fields
entityManager.persist(customer);
Order order = new Order();
order.setCustomer(customer);
// set order fields
entityManager.persist(order);
entityManager.flush();
```
在这个示例中,`Order`实体类使用了`@ManyToOne`注解来定义与`Customer`实体类的关系,使用了`@JoinColumn`注解来指定外键列的名称和是否允许为空。在保存`Order`实体时,先保存了对应的`Customer`实体,然后再将其设置为`Order`实体的关联属性,最后进行保存。
阅读全文