Null foreign key, in ManyToOne relation using hibernate [4.1.1] annotations

Laurențiu Onac picture Laurențiu Onac · Mar 24, 2012 · Viewed 12.8k times · Source

I am trying to persist a one-to-many and a many-to-one relation using Hibernate 4.1.1 but the foreign key is always NULL.

There are two entities: Account and Client. A Client could have multiple Accounts while an Account has exactly one Client.

Here are the classes (only what matters):

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();

While running, Hibernate adds the foreign key to the table:

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

Both accounts have id_client column NULL.

I tried putting nullable = false at the @JoinColumn relation but that just invoked an exception.

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

Answer

Laurențiu Onac picture Laurențiu Onac · Mar 25, 2012

Figured it out. I forgot to add the client to the accounts.

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

Now it works. Thank you for the tips. ;)