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

二次信任 提交于 2019-12-05 02:52:37

问题


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


回答1:


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




回答2:


I think issue is that you need to save account first and in the last client will be saved.



来源:https://stackoverflow.com/questions/9850566/null-foreign-key-in-manytoone-relation-using-hibernate-4-1-1-annotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!