Search code examples
javahibernatespringspring-mvcspring-roo

Spring roo Hibernate update entry many to many mapping


I have created a many to many mapping in spring roo between two entities Person and car and as expected I see a new table Person_Car. Below is the code in Person.java

@ManyToMany(cascade = CascadeType.ALL, mappedBy = "persons")
private Set<Car> cars= new HashSet<Car>();

Now I want to add entries in the table. I set the cars to the person object and do person.merge().

@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{        
...   
Person person = Person.findPerson(personId);  
Set<Car> cars = person.getCars();
        for(int i=0 ; i<temp.length ; i++){
            carID = Long.parseLong(temp[i]);
            cars.add(Car.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);
}

However, no entries are being made in the Person_Car table. But, when I do something like

Person person = Person.findPerson(personId);
person.setName("Jonathan");
person.merge();

I see the change reflected in the person table. What am I doing wrong? Thanks


Solution

  • Try to add @Transactional(rollback=false) to your controller method.

    rollback=false is default so you can skip it, and only @Transactional is left.