【问题标题】:Null foreign key, in ManyToOne relation using hibernate [4.1.1] annotations空外键,在 ManyToOne 关系中使用休眠 [4.1.1] 注释
【发布时间】:2012-04-08 16:24:54
【问题描述】:

我正在尝试使用 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;
    }
}

Client.java

@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

我尝试将 nullable = false 放在 @JoinColumn 关系中,但这只是引发了一个异常。

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

【问题讨论】:

  • 尝试在关系的账户端添加@NotNull注解

标签: java hibernate foreign-keys one-to-many many-to-one


【解决方案1】:

想通了。我忘记将客户添加到帐户中。

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

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

【讨论】:

  • 浪费了四个小时才发现我需要这样做。谢谢。
  • 你真的救了我的命……我想把头撞到墙上
  • 我以为这是自动完成的,它修复了列'id_client'不能为空
【解决方案2】:

我认为问题是您需要先保存帐户,然后才能保存最后一个客户。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    相关资源
    最近更新 更多