在模型上手动设置外键

时间:2018-07-25 14:10:25

标签: java hibernate spring-boot

我有多个一对一关系,当我要手动设置外键时,保存设置表存在问题。看起来像这样:

@Table(name = "User")
public class User {
    @Column(name = "userColumnName")
    private String userColumnName;
    @OneToOne(mappedBy = "settingColumnName")
    private Settings setting;
}

@Table(name = "Account")
public class Account {
    @Column(name = "accountColumnName")
    private String accountColumnName;
    @OneToOne(mappedBy = "settingColumnName")
    private Settings setting;
}

@Table(name = "Settings")
public class Settings{
    @Column(name = "userColumnName")
    private String userColumnName;

    @Column(name = "accountColumnName")
    private String accountColumnName;

    @OneToOne()
    @JoinColumn(insertable=false,updatable=false, name = "userColumnName")
    private User user;

    @OneToOne()
    @JoinColumn(insertable=false,updatable=false, name = "accountColumnName")
    private Account account;

    public void setUserColumnName(String id) {
        this.userColumnName = id
    }

    public void setAccountColumnName(String id) {
       this.accountColumnName = id;
    }

    public String getUserColumnName() {
        return userColumnName;
    }

    public String getAccountColumnName() {
        return userColumnName;
    }
}

我必须手动设置外键,因为所有这些模型都需要彼此独立地创建,因此在需要创建设置时,我已经在数据库中保存了帐户和用户模型。< / p>

无论如何,当我尝试这样做时:

settingsModel.setAccountColumnName("1121-12121-1221");
settingsModel.setUserColumnsName(null);
settingsModels.save();

数据库(h2)抱怨:Caused by: org.h2.jdbc.JdbcSQLException: Hexadecimal string contains non-hex character。尽管该列是作为VARCHAR创建的,但我无法用字符串ID填充这两个列。我什至尝试直接在数据库中输入字符串,但还是一样。我这样做正确,还是有更好的方法手动保存外键?

0 个答案:

没有答案