Я видел примеры, которые показывают, как сделать CRUD с одним объектом домена без вложенных объектов домена (только примитивы).Проблема заключается в том, как сделать то же самое с объектом домена, который имеет ссылки на другие объекты домена.Приведем следующий пример:
@Entity
public class Person implements Serializable {
@Id
private Long id;
private String name;
private Integer age;
private Address address;
private MaritalStatus maritalStatus;
... //getters/setters
}
@Entity
public class MaritalStatus implements Serializable {
@Id
private Long id;
private String description;
... //getters/setters
}
@Entity
public class Address implements Serializable {
@Id
private Long id;
private String street;
private String state;
private String zip;
... //getters/setters
}
Допустим, у меня есть форма, которая создает или обновляет Person, и запрашивает следующие данные:
Имя: _ _
Возраст: _ ____
Улица: _ __
Состояние: _ ____
Почтовый индекс: _ __ _
Семейное положение: (выбор ввода с соответствующим ключом (id объекта) / значением)
Итак, как вы можете создавать или обновлять, имея вложенные свойства, которые тоже имеют свою собственную идентичность (сохраняется)в другой таблице).
Я думал что-то вроде этого, используя метод prepare и paramsPrepareParamsStack:
public class PersonAction extends ActionSupport {
public String save() {
personService.save(person);
return SUCCESS;
}
public String update() {
personService.update(person);
return SUCCESS;
}
public void prepare() {
if (person.getId() != null) {
//find the person using the id.
Person p = personService.findById(person.getId());
//Update the reference to the selected martial status
//find the maritalstatus selected from the select box
MaritalStatus maritalStatus =
maritalStatusSerivce.findById(person.getMaritalStatus().getId());
//set the reference to the obtained person
p.setMaritalStatus(maritalStatus);
//find the address (in case it already exist)
if (person.getAddress().getId() != null) {
//find the address
Address address = addressService.findById(person.getAddress().getId());
//set the reference
p.setAddress(address);
}
//finally set the obtained reference to the action person property
this.person = p;
} else { //New person
//Find the address for the person
if (person.getAddress().getId() != null) {
//Only set the reference to the selected marital status
//find the maritalstatus selected from the select box
MaritalStatus maritalStatus =
maritalStatusSerivce.findById(person.getMaritalStatus().getId());
//set the reference to the person
person.setMaritalStatus(maritalStatus);
}
}
}
private Person person;
//getter/setters
}
Это правильный путь?Любой другой предложенный подход?
Спасибо