如何使用Hibernate和JPA使用父对象自动保存子对象?

时间:2015-04-29 14:25:05

标签: java hibernate jpa hibernate-mapping

我有onetoone协会。子类具有外键,该外键是父类中的主键。我的问题是我无法使用父类保存子类的对象。

我的添加方法如下:

@Transactional
public void add(ParentDTO parentDTO) {
    parentDTO.setChild(child);
    child.setParent(parentDTO);
    Parent parent = mapper.map(parentDTO, Parent.class);
    parentRepository.save(parent);
}

JSP代码如下;

<form:form action="user.do" method="POST" commandName="user">
<table>
    <tr>
        <td>User ID</td>
        <td><form:input path="userId" /></td>
    </tr>
    <tr>
        <td>Username</td>
        <td><form:input path="username" /></td>
    </tr>
    <tr>
        <td>Password</td>
        <td><form:password path="password" /></td>
    </tr>
    <tr>
        <td>First Name</td>
        <td><form:input path="firstName" /></td>
    </tr>
    <tr>
        <td>Last Name</td>
        <td><form:input path="lastName" /></td>
    </tr>
    <tr>
        <td>Active</td>
        <td><form:checkbox path="active" /></td>
    </tr>
    <tr>
        <td>ID</td>
        <td><form:label path="ethnicity.ethnicityId" /></td>
    </tr>
    <tr>
        <td>Nationality</td>
        <td><form:input path="ethnicity.nationality" /></td>
    </tr>
    <tr>
        <td>Race</td>
        <td><form:input path="ethnicity.race" /></td>
    </tr>
    <tr>
        <td>Region</td>
        <td><form:input path="ethnicity.region" /></td>
    </tr>
    <tr>
        <td>Religion</td>
        <td><form:input path="ethnicity.religion" /></td>
    </tr>
            <tr>
        <td colspan="2">
            <input type="submit" name="action" value="Add" />
            <input type="submit" name="action" value="Edit" />
            <input type="submit" name="action" value="Delete" />
            <input type="submit" name="action" value="Search" />
        </td>
    </tr>
</table>

控制器代码

@RequestMapping(value="/user.do", method=RequestMethod.POST)
public String doActions(@ModelAttribute UserDTO user,
        BindingResult result, @RequestParam String action,
        Map<String, Object> map){
    UserDTO userResult = new UserDTO();
    switch(action.toLowerCase()){
    case "add":
        userService.add(user);
        break;

1 个答案:

答案 0 :(得分:0)

您正在使用弹簧形式,因此在控制器中您将获得模型属性中的种族对象。

你可以如下所示:

childDTO.setNationality(user.getEthnicity().getNationality());

如果您使用的是servlet,则可以使用

获得价值
childDTO.setNationality(request.getParameter("nationality"));

在Spring控制器中还有其他方法来获取你的jsp输入:

   @Transactional
    public void add(ParentDTO parentDTO) {
//your child object should have all the property set here so that all values will be automatically inserted.
parentDTO.setChild(child);
child.setParent(parentDTO);
Parent parent = mapper.map(parentDTO, Parent.class);
parentRepository.save(parent);
//Even you can set property here

}