问题描述
当更新user表信息时,与user表记录相关联的access表中记录数据user_id被置空
主表:user
@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
@JoinColumn(name = "user_id",referencedColumnName = "id")
private List<UserAccess> accesses = new ArrayList<>();
副表:user-access
user_id外键关联主表的Id
@Column(name = "user_id")
private Long userId;
@Column(name="`key`", length = 32)
private String key;
@Column(name="`value`",length = 32)
private String value;
原因分析:
查看日志
Hibernate: select user0_.id as id1_6_0_, user0_.created_at as created_2_6_0_, user0_.updated_at as updated_3_6_0_, user0_.email as email4_6_0_, user0_.locked as locked5_6_0_, user0_.locked_at as locked_a6_6_0_, user0_.mobile as mobile7_6_0_, user0_.name as name8_6_0_, user0_.password as password9_6_0_, user0_.profile as profile10_6_0_, user0_.real_name as real_na11_6_0_, user0_.remark as remark12_6_0_, user0_.token as token13_6_0_ from users user0_ where user0_.id=?
Hibernate: select role0_.id as id1_3_, role0_.created_at as created_2_3_, role0_.updated_at as updated_3_3_, role0_.locked as locked4_3_, role0_.locked_at as locked_a5_3_, role0_.name as name6_3_, role0_.remark as remark7_3_ from roles role0_ where role0_.id in (?)
Hibernate: update users set created_at=?, updated_at=?, email=?, locked=?, locked_at=?, mobile=?, name=?, password=?, profile=?, real_name=?, remark=?, token=? where id=?
Hibernate: update user_accesses set user_id=null where user_id=?
Hibernate: delete from users_roles where user_id=?
Hibernate: insert into users_roles (user_id, role_id) values (?, ?)
sql中对user_id置空
解决方案:
去翻看了一些博客,试过把 cascade = CascadeType.ALL改成 CascadeType.REMOVE,但是没有效果
也试过 加 mappedBy ,还有在子表中加上注解。
因为本人初次接触jpa,所以有些概念还不是很明白。按照业务来说驱动表应该是user,想要实现的效果应该是删除user后,与之想关联的access表中的数据也随之删除。
@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
//在注解中加上updatable = false,得到解决,但是不清楚其他影响
@JoinColumn(name = "user_id",referencedColumnName = "id",updatable = false)
private List<UserAccess> accesses = new ArrayList<>();
如果有知道的朋友欢迎解惑