防止在春季休眠时使用OneToOne关系在父表中插入空值

穆罕默德·侯赛因

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

用户类别:

    @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---
}

PrfilePic类别:

@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);
    }

控制器类:

@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=?

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

坦率

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

但是,如果要使用用户ID将数据插入ProfilePic,则还需要将关联的用户插入到用户表中,否则用户ID将不可用。

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

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

您将遇到一个错误(无法添加或更新子行:外键约束失败(stackoverflowprofile_pic,CONSTRAINT user_idFOREIGN KEY(user_id)参考useruser_id)))因此,基本上没有ID为1的用户。

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

您应该将模型更改为类似以下内容:用户类:

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

ProfilePic类:

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用休眠保存父表时在外键中插入Null

休眠:单表中的父/子关系

休眠与OneToOne关系-仅保留父实体

在“一对多”映射中,休眠数据在更新父表时被插入到子表中

使用父表中的值而不是 ID 的 Django 批量插入

使用 JOOQ 在多对多关系表中插入值

使用休眠将行插入数据库时,我将“ 1”和空值(而不是用户输入的值)放入数据库中

休眠-@OneToOne关系

当文本框值为空时,使用 C# 停止在表中插入空值日期

休眠是使用apache-poi在外键字段中插入空值

在表关系Laravel中插入值

父ID不会插入到Java休眠中的子表Whit OneToMany关系中

休眠:防止在并行处理时重复插入?

休眠@OneToOne为空

使用mySQL odbc连接器从ASP.NET触发插入查询时,空值将存储在mySQL表中

在父表中插入值时自动在子表中生成ID

使用JPA查询可为空的@OneToOne关系

当父表的值都存储到数组中时,如何将数组插入到联结表中?

使用MapsId映射的OneToOne关系时,findAll()方法不返回最近插入的记录

防止将数组中的空值插入Mongo集合

使用更大的表还是OneToOne关系?

如何使用python在表中插入一行值(不是空值?

休眠同一表的父/子关系

仅在表为空时插入表中

使用EF Core插入对象时,“无法为表中的标识列插入显式值”

休眠创建空表-启动时休眠

在表中插入记录时在MySql中查询空异常

仅当使用MySQL的值不存在时才如何从表中插入值?

使用休眠从表中获取单个日期值