【发布时间】:2011-06-26 21:02:23
【问题描述】:
我有类似Spring Framework - New object is created in DB instead of updating 中描述的问题,但我有两个实体:Author 和Department 关系中的@ManyToOne。一个部门有很多作者,一个作者属于一个部门。当我更新作者时,作者详细信息会更新,但会插入部门,这会导致重复条目。从上述链接中,我知道我可能缺少部门 ID,但我不知道如何将部门与其 ID 联系起来。
作者实体(没有 getter 和 setter)
@Entity
@Table(name = "author")
public class Author implements Serializable {
@Id
@Column(name = "idauthor")
@GeneratedValue
private Integer idAuthor;
@Column(name = "name")
private String name;
@ManyToOne(cascade = CascadeType.ALL)
private Department department;
}
部门实体(没有getter和setter)
@Entity
@Table(name="department")
public class Department implements Serializable {
@Id
@Column(name="iddepartment")
@GeneratedValue
private Integer iddepartment;
@Column(name="name", unique=true)
private String name;
}
AuthorController中Author的更新操作方法
@Controller
@RequestMapping("/author")
public class AuthorController {
@Autowired
private AuthorService authorService;
@Autowired
private DepartmentService departmentService;
@RequestMapping(value="/save/{authorId}", method = RequestMethod.GET)
public String renderUpdateForm(@PathVariable("authorId") Integer authorId, ModelMap model) {
model.addAttribute("author", authorService.getAuthorByID(authorId));
model.addAttribute("departmentList", departmentService.listDepartment());
return "author.save";
}
@RequestMapping(value="/save/{authorId}", method = RequestMethod.POST)
public String updateAuthor(@ModelAttribute("idAuthor") Author author, BindingResult result, SessionStatus status) {
authorService.updateAuthor(author);
status.setComplete();
return "redirect:/author";
}
}
authorService.updateAuthor(author); 调用服务,该服务使用方法调用 DAO 类:
@Repository
@Transactional
public class AuthorDAOImpl implements AuthorDAO {
@Autowired
private SessionFactory sessionFactory;
@Override
public void updateAuthor(Author author) {
sessionFactory.getCurrentSession().update(author);
}
}
最后是带有表单的 JSP
<form:form method="post" action="${pageContext.request.contextPath}/author/save" modelAttribute="author">
<form:hidden path="idAuthor" />
<table>
<tr>
<td>
<form:label path="name">
<spring:message code="label.author.name"/>
</form:label>
</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>
<form:label path="department.name">
<spring:message code="label.author.department"/>
</form:label>
</td>
<td>
<form:select path="department.name">
<form:options items="${departmentList}" itemValue="name" itemLabel="name" />
</form:select>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="<spring:message code="label.update" />
</td>
</tr>
</table>
</form:form>
我得到的错误是
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 重复条目'自定义部门 键'名称'的名称'
我应该如何将 ID 传递给部门或解决我的问题?感谢您的建议。
【问题讨论】:
标签: hibernate spring spring-mvc