使用hibernate [4.1.1]注释在ManyToOne关系中使用Null外键

Lau*_*nac 3 java hibernate foreign-keys one-to-many many-to-one

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

有两个实体:帐户客户.一个客户可以有多个账户,而一个帐户只能有一个客户端.

这是课程(只有重要的):

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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();
Run Code Online (Sandbox Code Playgroud)

在运行时,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

Lau*_*nac 8

弄清楚了.我忘了将客户端添加到帐户中.

account1.setClient(client);
account2.setClient(client);
Run Code Online (Sandbox Code Playgroud)

现在它有效.感谢您的小费.;)