I am having an issue in persisting an Object with a ManyToOne relationship using spring jpa.
These are my classes.
Parent Class
@Entity
@Table(name = "PROVINCE")
public class Province {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "PROVINCE_ID")
private long id;
private String name;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "province", targetEntity = Town.class)
@JsonManagedReference("Province-Town")
private List<Town> towns;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Town> getTowns() {
return towns;
}
public void setTowns(List<Town> towns) {
this.towns = towns;
}
}
Child Class
@Entity
@Table(name = "TOWN")
public class Town {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "TOWN_ID")
private long id;
private String name;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "PROVINCE_ID")
@JsonBackReference("Province-Town")
private Province province;
private long kiloMeter;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Province getProvince() {
return province;
}
public void setProvince(Province province) {
this.province = province;
}
public long getKiloMeter() {
return kiloMeter;
}
public void setKiloMeter(long kiloMeter) {
this.kiloMeter = kiloMeter;
}
}
FYI, I already have repositories and services for the respective classes.
My RestController for creating my Town Entity is..
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Void> create(@RequestBody Town town, UriComponentsBuilder ucBuilder) {
if (townService.isTownExists(town)) {
LOGGER.info("Unable to save {}. Town already exists", town.getName());
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
townService.save(town);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path(BASE_PATH + "/{id}").buildAndExpand(town.getId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
The issue is I want to post the object together with the parent entity (Province).
Assuming that I already persisted a Province with an id of 1. The JSON body that I am sending in POSTMAN is this.
{
"name" : "Some Town",
"province" : {
"id" : 1
},
"kiloMeter" : 340
}
However I get the error.
"exception": "org.springframework.dao.InvalidDataAccessApiUsageException",
"message": "detached entity passed to persist: org.pipecrafts.busnet.model.location.misc.Province; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: org.pipecrafts.busnet.model.location.misc.Province",
When I send a request like this it is successful.
{
"name" : "Some Town",
"kiloMeter" : 340
}