gpt4 book ai didi

mysql - 在 spring hibernate 中使用 OneToOne 关系防止在父表中插入空值

转载 作者:行者123 更新时间:2023-11-30 21:30:14 24 4
gpt4 key购买 nike

我有两个具有 OneToOne 关系双向映射的表 User 和 ProfilePic。为用户上传个人资料图片时,它会在数据库中创建具有空值的新用户。我需要防止插入新用户并且只想在 ProfilePic 表中插入值。请不要标记为重复或否决我是 hibernate 新手。相关代码如下:

用户类别:

    @Entity
@Table(name = "user_details")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int userId;
private String firstName;
private String lastName;
private String gender;
@Temporal(TemporalType.DATE)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date dob;
private String email;
private String address;
private String username;
private String password;
private String phoneNumber;
private Boolean isActive;
private String role;
@OneToOne(mappedBy = "user")
private ProfilePic profilePic;
@OneToMany(mappedBy = "user")
private List<Login> login = new ArrayList<>();

-----getter setter---
}

个人资料图片类:

@Entity
public class ProfilePic {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int imageId;
private String image_url;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "userId", nullable = false)
private User user;
---getter setter---
}

存储库类:

@Override
public void saveProfilePic(ProfilePic profilePic) {
HibernateUtil.getSession(sessionFactory).save(profilePic);
}

Controller 类:

@RequestMapping(value = "/uploadProfileimage", method = RequestMethod.POST)
public String uploadProfileImage(@ModelAttribute User user, @ModelAttribute ProfilePic profilePic,
@RequestParam("image") CommonsMultipartFile file, Model model) {
String imageUrl = "";
if (!file.getOriginalFilename().isEmpty()) {
imageUrl = ImageUtil.writeImageToFile(file);
profilePic.setImage_url(imageUrl);
profilePic.setUser(user);
pictures.add(profilePic);
userService.saveProfilePic(profilePic);
}
return "redirect:/getProfile?userId=" + user.getUserId();
}

日志:

Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into user_details (address, dob, email, firstName, gender, isActive, lastName, password, phoneNumber, role, username, userId) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into ProfilePic (image_url, userId, imageId) values (?, ?, ?)
Hibernate: select user0_.userId as userId1_7_0_, user0_.address as address2_7_0_, user0_.dob as dob3_7_0_, user0_.email as email4_7_0_, user0_.firstName as firstNam5_7_0_, user0_.gender as gender6_7_0_, user0_.isActive as isActive7_7_0_, user0_.lastName as lastName8_7_0_, user0_.password as password9_7_0_, user0_.phoneNumber as phoneNu10_7_0_, user0_.role as role11_7_0_, user0_.username as usernam12_7_0_, profilepic1_.imageId as imageId1_6_1_, profilepic1_.image_url as image_ur2_6_1_, profilepic1_.userId as userId3_6_1_ from user_details user0_ left outer join ProfilePic profilepic1_ on user0_.userId=profilepic1_.userId where user0_.userId=?

预期结果:仅在 ProfilePic 表中插入数据并关联用户 ID实际结果:User和ProfilePic这两个表都插入了数据。创建的新用户在所有列中均具有空值。帮助将不胜感激。我深陷其中。

最佳答案

问题是,如果用户 id 为 null,则只在 ProfilePic 中插入数据不是问题,因此没有用户与此图片相关联。

但是如果要向ProfilePic中插入数据时,需要将用户id插入到用户表中,否则用户id将不可用。

因此,例如在 MYSQL 中,如果您运行此查询:

INSERT INTO profile_pic (image_id, image_url, user_id) VALUES ('1', "/image", '1');

您将遇到错误(无法添加或更新子行:外键约束失败(stackoverflowprofile_pic,CONSTRAINT user_id 外键 (user_id) 引用 user (user_id)))所以基本上没有id为1的用户。

解决方案是使用单向映射,换句话说,用户将引用profile_pic,但profile_pic不会。

您应该将模型更改为:用户类:

    @Entity
@Table(name = "user_details")
public class User {
@OneToOne
private ProfilePic profilePic;
// other fields, getters and setters
}

个人资料图片类:

@Entity
public class ProfilePic {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int imageId;
private String image_url;
// getters and setters
}

然后您将只能插入 ProfilePic。我希望这对你有用!

关于mysql - 在 spring hibernate 中使用 OneToOne 关系防止在父表中插入空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56645901/

24 4 0
文章推荐: php - 如果用户已经存在,如何替换一些值?
文章推荐: c++ - 保存AVL树中节点下的叶子数
文章推荐: C 将字符串分割成int数组
文章推荐: c# - RestSharp Deserialize List 返回 Could not cast or convert from System.String to