作为序言,我是休眠的新手(通常是Java),所以请耐心等待。因此,我尝试设置两个实体,Driver和Address,其中多个驱动程序可以具有相同的地址(因此,ManyToOne)。我在网上阅读的所有内容都是关于一对多的关系,但在其他方面却找不到。我希望能够使用具有相同地址的不同驱动程序向我的端点发出发布请求,而无需创建重复的地址条目。这里分别是(略略的)Driver和Address实体以及DriverService。
当我从地址表中删除uniqueConstraints时,我可以向端点发出多个发布请求,并在数据库中重复相同的地址。我希望能够发出多个发布请求,并使所有具有相同地址的驱动程序链接到数据库中的单个地址,而不仅仅是继续进行重复的输入。我想念什么?
@Entity
@Table(name = "driver")
public class Driver implements Serializable {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(cascade = CascadeType.ALL,
fetch = FetchType.EAGER)
public Address getAddress() {
return address_id;
}
@Entity
@Table(name = "address",
uniqueConstraints = @UniqueConstraint(columnNames = {"street", "city", "state", "zip"}))
public class Address implements Serializable {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Service
公共类DriverService {
private final DriverRepository driverRepository;
public DriverService (DriverRepository driverRepository) {
this.driverRepository = driverRepository;
}
public Driver createDriver(DriverDTO dto) {
Address address = new Address();
DriversLicense driversLicense = new DriversLicense();
Driver driver = new Driver();
address.setStreet(dto.getStreet());
address.setCity(dto.getCity());
address.setState(dto.getState());
address.setZip(dto.getPostal());
Date issueDate = new Date();
Date expDate = new Date();
Date dob = new Date();
try {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
issueDate = sdf.parse(dto.getIssued());
expDate = sdf.parse(dto.getExpires());
dob = sdf.parse(dto.getDob());
}
catch (ParseException e) {
e.printStackTrace();
}
driversLicense.setDriversLicenseNumber(dto.getId());
driversLicense.setIssuedDate(issueDate);
driversLicense.setExpirationDate(expDate);
driver.setFirstName(dto.getFirst());
driver.setLastName(dto.getLast());
driver.setMiddleName(dto.getMiddle());
driver.setBirthDate(dob);
driver.setEyeColor(dto.getEyes());
driver.setGender(dto.getSex());
driver.setHeight(dto.getHeight());
driver.setAddress(address);
driver.setDriversLicense(driversLicense);
driverRepository.save(driver);
return driver;
}
}