小编典典

空外键,在使用休眠[4.1.1]批注的ManyToOne关系中

hibernate

我试图使用 Hibernate 4.1.1 保持一对多和多对一关系,但外键始终为 NULL

有两个实体: AccountClient 。一个 客户 可以有多个 帐户, 而一个 帐户 恰好有一个 客户

这些是类(仅重要的部分):

Account.java

@Entity
@Table(name = "account")
public class Account implements Serializable {
    private Client client;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    public long getId() {
        return id;
    }

    @ManyToOne
    @JoinColumn(name = "id_client")
    public Client getClient() {
        return client;
    }
}

客户端程序

@Entity
@Table(name = "client")
public class Client implements Serializable {
    private List<Account> accounts;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    public long getId() {
        return id;
    }

    @OneToMany(mappedBy = "client", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    public List<Account> getAccounts() {
        return accounts;
    }
}

Test.java

session.beginTransaction();

Client client = new Client();
Account account1 = new Account();
Account account2 = new Account();

a.addAccount(account1);
a.addAccount(account2);

session.save(client);
session.getTransaction().commit();

运行时,Hibernate将外键添加到表中:

Hibernate: alter table account add index FKB9D38A2D3B988D48 (id_client), add constraint FKB9D38A2D3B988D48 foreign key (id_client) references client (id)

两个帐户的id_client列均为 NULL

我尝试在@JoinColumn关系上放置 nullable = false ,但这只是调用了一个异常。

Exception in thread "main" org.hibernate.exception.ConstraintViolationException: Column 'id_client' cannot be null


阅读 232

收藏
2020-06-20

共1个答案

小编典典

弄清楚了。我忘记了将客户添加到帐户中。

account1.setClient(client);
account2.setClient(client);

现在可以了。感谢您的小费。;)

2020-06-20