Null foreign key, to ManyToOne using hibernate annotations [4.1.1]

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

There are two objects: account and client. A customer can have multiple accounts, while an account has exactly one customer.

Here are the classes (just what's important):

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

      

At runtime, Hibernate adds a 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 a NULL id_client column.

I tried to put nullable = false in the @JoinColumn relationship but just threw an exception.

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

+3


source to share


2 answers


Found it out. I forgot to add a client to accounts.

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

      



Now it works. Thanks for the tips.;)

+7


source


I think the problem is that you need to save the account first, and the last client will save.



0


source







All Articles