0 0

hibernate4 外键级联删除cascade="delete"属性失效不起作用5

下面是我的两个映射文件:
Blog:
<class name="Blog" table="blog">
<id name="id" column="id">
<generator class="identity"></generator>
</id>
<property name="title" type="string" column="title"></property>
<property name="content" type="string" column="content"></property>
<property name="datetime" type="date" column="createTime"></property>
<set name="comments" inverse="true" cascade="delete">
<key column="blogId"></key>
<one-to-many class="Comment"/>
</set>
</class>

Comment:
<class name="Comment" table="comment">
<id name="id" column="id">
<generator class="identity"></generator>
</id>
<property name="user" type="string" column="user"></property>
<property name="email" type="string" column="email"></property>
<property name="url" type="string" column="url"></property>
<property name="content" type="string" column="content"></property>
<property name="datetime" type="date" column="createTime"></property>
<many-to-one name="blog" class="Blog" column="blogId" not-null="true"></many-to-one>
</class>

当我运行程序的时候打印出来hibernate执行的sql语句是这样的:
Hibernate:
    alter table comment
        drop
        foreign key FK38A5EE5FDE0F1321
Hibernate:
    drop table if exists blog
Hibernate:
    drop table if exists comment
Hibernate:
    create table blog (
        id integer not null auto_increment,
        title varchar(255),
        content varchar(255),
        createTime date,
        primary key (id)
    ) type=InnoDB
Hibernate:
    create table comment (
        id integer not null auto_increment,
        user varchar(255),
        email varchar(255),
        url varchar(255),
        content varchar(255),
        createTime date,
        blogId integer not null,
        primary key (id)
    ) type=InnoDB
Hibernate:
    alter table comment
        add index FK38A5EE5FDE0F1321 (blogId),
        add constraint FK38A5EE5FDE0F1321
        foreign key (blogId)
        references blog (id)

而我认为正确的情况下。最后一节添加外键关系的SQL语句应该是这样的:
    alter table comment
        add index FK38A5EE5FDE0F1321 (blogId),
        add constraint FK38A5EE5FDE0F1321
        foreign key (blogId)
        references blog (id)
        on delete cascade

结果我在删除Blog的时候抛出如下异常:
Cannot delete or update a parent row: a foreign key constraint fails (`blog/comment`, CONSTRAINT `FK38A5EE5FDE0F1321` FOREIGN KEY (`blogId`) REFERENCES `blog` (`id`))


我程序的main方法具体如下:
public static void main(String[] args) {
Session session = HibernateUtil.currentSession();
Blog blog = new Blog();
blog.setTitle("a title");
session.save(blog);
Comment comment = new Comment();
comment.setContent("good");
comment.setBlog(blog);
session.save(comment);
session.delete(blog);
session.flush();
HibernateUtil.closeSession();
}

1个答案 按时间排序 按投票排序

0 0

楼主,问题解决了没有

2017年8月14日 22:31

相关推荐

Global site tag (gtag.js) - Google Analytics