以下是客户类,因为您可以看到它具有对地址对象的引用,在基础客户表中它是地址的ID。我省略了getter和setter以及一些简单的变量。
@Entity
@Table(name = "customer")
public class Customer implements Serializable {
@Id
@GeneratedValue
@Column(name = "customer_id")
private int customerId;
@ManyToOne
@JoinColumn(name = "store_id")
private Store store;
@ManyToOne
@JoinColumn(name = "address_id")
private Address address;
........
}
以下是地址类。
//Address Class
@Entity
@Table(name = "address")
public class Address implements Serializable {
@Id
@GeneratedValue
@Column(name = "address_id")
private int addressId;
@JoinColumn(name = "city_id")
@ManyToOne
private City city;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "address")
@JsonIgnore
List<Customer> customers;
......
}
我尝试在一次通话中坚持新客户和新地址,如下所示。我省略了一些我设定的变量。
Customer cus = new Customer();
Address addr= new Address();
........
cus.setAddress(addr)
List<Customer> cusList= new ArrayList<>();
cusList.add(cus);
addr.setCustomers(cusList);
entityManager.persist(cus)
但是我得到一个错误,说客户表中的address_id为空。我原本以为JPA会插入新地址然后插入新客户,地址id列设置为新地址ID?我的想法在这里错了吗?或者我在映射中犯了错误或者我如何坚持实体?
我能做到这一点的另一种方法是先坚持地址然后坚持客户,但如果可能的话,我宁愿在一个坚持下做。
以下是基础表格。
//Customer Table
CREATE TABLE `customer` (
`customer_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`store_id` tinyint(3) unsigned NOT NULL,
`first_name` varchar(45) NOT NULL,
`last_name` varchar(45) NOT NULL,
`email` varchar(50) DEFAULT NULL,
`address_id` smallint(5) unsigned NOT NULL,
`active` tinyint(1) NOT NULL DEFAULT '1',
`create_date` datetime NOT NULL,
`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`customer_id`),
KEY `idx_fk_store_id` (`store_id`),
KEY `idx_fk_address_id` (`address_id`),
KEY `idx_last_name` (`last_name`),
CONSTRAINT `fk_customer_address` FOREIGN KEY (`address_id`) REFERENCES `address` (`address_id`) ON UPDATE CASCADE,
CONSTRAINT `fk_customer_store` FOREIGN KEY (`store_id`) REFERENCES `store` (`store_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=608 DEFAULT CHARSET=utf8;
/Address Table
CREATE TABLE `address` (
`address_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`address` varchar(50) NOT NULL,
`address2` varchar(50) DEFAULT NULL,
`district` varchar(20) NOT NULL,
`city_id` smallint(5) unsigned NOT NULL,
`postal_code` varchar(10) DEFAULT NULL,
`phone` varchar(20) NOT NULL,
`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`address_id`),
KEY `idx_fk_city_id` (`city_id`),
CONSTRAINT `fk_address_city` FOREIGN KEY (`city_id`) REFERENCES `city` (`city_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=619 DEFAULT CHARSET=utf8;
感谢。
答案 0 :(得分:1)
如果您要使用Address
保存新的Customer
,则需要添加CascadeType.ALL
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "address_id")
private Address address;
以这种方式保存所有内容(您不需要将客户添加到地址列表中,因为客户仅通过外键address_id
来引用该地址)
Customer cus = new Customer();
Address addr = new Address();
cus.setAddress(addr)
entityManager.persist(cus)
但这不是一种非常方便的方式,因为地址就像引用一样。因此,通过保存每个客户更新参考地址是不常见的。