Hibernate级联添加的问题
一位同学问过我这样一个问题:
现有用户实体类、帖子实体类、评论实体类,现在要给帖子添加评论,但是评论既级联了帖子,又级联了用户,现在他的测试程序时这样的:
(com 是评论 POST是 帖子 )
DbDao db=DbDaoFactory.getDbDaoBean();
Post post=new Post();
ManageUser user=new ManageUser();
user.setUsername("11");
Comments com=new Comments();
post.setTitle("标题");
post.setState(1);
com.setPost(post);
com.setState(1);
com.setContent("评论");
com.setUser(user);
db.add(com);
下面是各自的配置文件:
评论的关系
<many-to-one name="post" class="Post" column="post_id" cascade="save-update"></many-to-one>
<many-to-one name="user" class="ManageUser" column="user_id" cascade="save-update"></many-to-one>
(配置文件是没有问题的)
但是执行完测试程序后,控制台输出:
Hibernate: select comments_auto.nextval from dual
Hibernate: select post_auto.nextval from dual
Hibernate: select manageuser_auto.nextval from dual
Hibernate: insert into post (title, state, example, example1, user_id, post_id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into manageuser (username, password, example, example1, manageuserid) values (?, ?, ?, ?, ?)
Hibernate: insert into comments (content, state, creattime, example, example1, post_id, user_id, comments_id) values (?, ?, ?, ?, ?, ?, ?, ?)
就是 在用户表、帖子表和评论表中同时各插入了一条记录,正常应该只在评论表中插入一条记录,该记录中包含用户id外键和帖子id外键,但现在为什么会这样呢??
原因在哪里??
现在你的用户和帖子都是瞬态对象,当然会级联添加!
正确的操作是:先得到持久化的用户对象和帖子对象 然后添加到评论中,这样就不会向用户表、帖子表中插入记录了。
浙公网安备 33010602011771号