Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 482
Laurențiu Onac Avatar asked Jan 18 '23 02:01

Laurențiu Onac


1 Answers

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

like image 98
Laurențiu Onac Avatar answered Jan 31 '23 07:01

Laurențiu Onac