Spring Framework - New object is created in DB instead of updatingに記載されているのと同様の問題がありますが、Author
とDepartment
の@ManyToOne
という2つのエンティティがあります。 1つの部門には多くの著者があり、1つの著者は1つの部門に所属しています。著者を更新すると、著者の詳細は更新されますが、部門が挿入されて重複したエントリにつながります。上記のリンクから、私はおそらく部門IDがないことを知っていますが、私は部門IDをどのように結ぶべきか分かりません。Springのフォームを介したdbデータの更新
(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
@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クラスをメソッドで呼び出すコールサービス: 重複エントリーのカスタム:フォーム
<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>
そして、私は取得していますエラーと
@Repository
@Transactional
public class AuthorDAOImpl implements AuthorDAO {
@Autowired
private SessionFactory sessionFactory;
@Override
public void updateAuthor(Author author) {
sessionFactory.getCurrentSession().update(author);
}
}
、最終的にはJSPは
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationExceptionです部門 キー名 'の名前'
IDを部門に渡すか、問題を解決する必要がありますか?あなたのアドバイスをありがとう。