问题描述
- Spring,Hibernate保存对象时的问题
- 有两个实体类User和Department。建立双向多对一关联。
User是多的一端
@Entitypublic class User implements Serializable{ @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name=""id"") private Integer id; @Column(name=""name"") private String name; @Column(name=""age"") private Integer age; @ManyToOne(cascade=CascadeType.ALL) @JoinColumn(name=""department_id"") private Department department;}
Department是一的一端
@Entitypublic class Department { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name=""id"") private Integer id; @Column(name=""name"") private String name; @OneToMany(mappedBy=""department"" cascade=CascadeType.ALL) private Set<User> user;}
数据库中有如图的数据:
User表:
Department表:
通过jsp新增一个User
<form:form action=""${pageContext.request.contextPath}/add"" method=""post"" commandName=""User""> <table> <tr> <td>Name:</td> <td><form:input path=""name""/></td> </tr> <tr> <td>Age:</td> <td><form:input path=""age""/></td> </tr> <tr> <td>Department:</td> <td><form:input path=""department.name""/></td> </tr> <tr> <td><input type=""submit""></td> </tr> </table></form:form>
Dao层里的代码
@Autowired private SessionFactory sessionFactory; private Session getSession(){ return sessionFactory.getCurrentSession(); } public void add(User user) { Session session = getSession(); session.save(user); }
结果数据库更新后是这样的
执行的SQL
Hibernate: insert into Department (name) values (?)
Hibernate: insert into User (age department_id name) values (? ? ?)
想要达到的效果是新增User的department_id应该还是已有的部门,而不是新建一个部门。请问是什么问题啊。
多谢了!!!
解决方案
你没有说清楚你遇到了什么问题
时间: 2024-11-01 10:27:56