简体   繁体   中英

Inserting a Hibernate entity with relationship

Say I have these classes:

public class Loan {
    @Id
    private Long id;

    @ManyToOne
    @JoinColumn(name = "lender_id")
    private User lender;
}

public class User {

    @Id
    private Long id;

    @Column
    private String userName;

    @OneToMany
    private List<Loan> loans;
}

Now, let's say I have the user (lender) id and in the DAO layer, I want to create a Loan based on the id of the lender?

I realize that I can do the following:

User u = userDao.getUserById(1234L);
loanDao.createLoan(u, "someLoan");

But I'm wondering if it's possible to do it without pre-loading the User record?

There isn't a good way to do that, in part because it would fundamentally lead to incorrect ORM code. You the programmer are responsible for managing the in memory state of the Entities and keeping them correct. If you create a new Loan and say it belongs to a User, and a User has a collection of Loans, it is your responsibility to add that Loan to the User! (This has real consequences as soon as the caches get involved.)

You're using ORM, you need to think in terms of the objects and not in terms of the database. Adding a number in a foreign key column isn't what's important, setting up the correct in-memory representation of the object Model is what's important for you. The database is hibernate's problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM