Say we have 2 classes Driver and Car with the Driver having a many-to-one relationship with the Car as follows.
@Entity
@Table(name = "driver")
public class Driver {
@Id @GeneratedValue
private Long id;
@ManyToOne
private Car car;
...
// getter setter ignored for brevity
}
Is there a way to set the value of car
via post request for example by referencing car
by its id
by just JPA/Hibernate annotations ? I'm still sort of new to Spring boot, so I was actually thinking of creating a new attribute Long carId
and then apply @JsonIgnore
to car
, according to https://stackoverflow.com/a/42633336/9324939 . Or is there any other suggestion or approach to get what I'm trying to achieve?
PS: In the database, they are already connected by reference.
-- in postgres
...
driver_id BIGINTEGER REFERENCES car (id)
...
please take a look here for a sample project I made to address this:
https://github.com/Fermi-4/StackOverflow---JPA-Relationships
Once started locally, use Postman to set the car to a driver:
http://localhost:9090/api/assigncar?driverId=1&carId=1
Driver Entity - using Lombok
@Entity
@Table(name = "driver")
@Data
public class Driver {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long driverId;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Car car;
}
Car Entity - using Lombok and @JsonIgnore to prevent infinite recursion
@Entity
@Table(name = "car")
@Data
public class Car {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long carId;
@JsonIgnore
@OneToMany
private List<Driver> drivers = new ArrayList<Driver>();
}
Repositories
public interface CarRepository extends JpaRepository<Car, Long> { }
public interface DriverRepository extends JpaRepository<Driver, Long> { }
Controller Class
@RequestMapping("/api")
@RestController
public class DriverController {
@Autowired
CarRepository _carRepo;
@Autowired
DriverRepository _driverRepo;
@PostMapping("/assigncar")
public Driver assignCarToDriver(@RequestParam Long driverId,@RequestParam Long carId) {
Car car = _carRepo.findById(carId).get();
Driver driver = _driverRepo.findById(driverId).get();
driver.setCar(car);
return _driverRepo.save(driver);
}
}
当您通过 post request 添加新司机时,您可以在您的 json 对象中分配一辆新车或一辆现有汽车(您可以尝试在您的 @ManyToOne 中添加 cascadeType.ALL)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.