jeudi 26 mars 2015

How to receive JSON data with relation to existing master record in Spring MVC/REST creation

I am new in Spring MVC / REST. My aim is to create REST endpoint that provide CRUD features and will be utilized by AngularJS. I faced problem when trying to handle creation of new Entity that has relation to other existing record that provided by HTML select (by its id).



@Entity
@Table(name="goal")
public class Goal {

private String title;

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="categoryId")
private Category category;

//getter setter ommited
}

@Entity
@Table(name="category")
public class Category {

private Long id;
private String name;

//getter setter ommited
}

//Controller
@RequestMapping(value = "/goals", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public MasterGoal create(@RequestBody Goal goal) {
goal = masterGoalService.saveGoal(goal);
return goal;
}


And here is the JSON from Angular:



//assumed that categoryId: 1 -> "Personal", already exist in the database
{
"title": "My Goal",
"categoryId": 1
}


This did not work. I also try to implement the suggestion from here, but it didn't work either. the conversion process wasn't triggered.



public class CategoryEditor extends PropertyEditorSupport {

private CategoryRepository repo;


public CategoryEditor(CategoryRepository repo) {
this.repo = repo;
}

@Override
public String getAsText() {
return super.getAsText();
}

@Override
public void setAsText(String text) throws IllegalArgumentException {
Category category = null;

try {
Long id = (long) Integer.parseInt(text);
category = repo.findOne(id);
} catch (NumberFormatException e) {
logger.debug("*** " + e.getMessage());
} catch (Exception e) {
logger.debug("*** " + e.getMessage());
}

this.setValue(category);
}

}

//In Controller
@InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
binder.registerCustomEditor(Category.class, new CategoryEditor(categoryRepo));
}


Are there any best practice to handle this kind of issue?


Aucun commentaire:

Enregistrer un commentaire