Say, I have two tables Person and Car and I link these two. The following code is in Person.java
@ManyToMany(cascade = CascadeType.ALL, mappedBy = "persons")
private Set<Car> cars= new HashSet<Car>();
I see a table created CAR_PERSON but there is no class created. So how am I to add a list of cars to a person. I have gone until getting the required person object and creating cars but how do I add it to the table. I tried using person.merge after assigning the set of cars to the person object but there were no entries in the table. I started on this Spring Roo project just yesterday, so please excuse my ignorance :) Below is the code I wrote for linking the cars to the person. This is in the PersonController
@RequestMapping(value ="/saveCars", method = RequestMethod.POST)
@ResponseBody
public String saveCars(@RequestParam("personId")Long personId, @RequestParam("cars") String incomingCars){
Map<String, Object> response = new HashMap<String, Object>();
try{
...
for(int i=0 ; i<temp.length ; i++){
carID = Long.parseLong(temp[i]);
cars.add(Product.findCar(carID));
}
person.setCars(cars);
person.merge();
}
LOG.debug("cars successfully added to questionnaire");
response.put("message", "success");
}
return new JSONSerializer().exclude("*.class").deepSerialize(response);
}
I would let Roo
manage the saving itself if you don't want to add anything extra when you save. I would recommend you add the field cars to persons using the Roo shell
. Then Roo
will automatically modify the controllers
to add the list of cars to person