Hibernate, insert or update without select

后端 未结 3 1415
温柔的废话
温柔的废话 2021-02-20 05:51

I have a products objects which belongs to certain categories i.e. classical many to one relationship.

@Entity
public class Product{

    @Id
    @GeneratedValue         


        
相关标签:
3条回答
  • 2021-02-20 05:52

    I've just tried following:

    Category category = new Category(categoryId);
    product.setCategory(category);
    

    And it worked, i mean product record in db got correct link to category and category with id

    categoryId
    

    haven't changed.

    0 讨论(0)
  • 2021-02-20 05:53

    session.load() exists specifically for cases like this. The following:

    Category category = session.load(categoryId);
    product.setCategory(category);
    

    will not hit the database. It will, however, throw an exception at a later stage (during flush, more or less) if there is no category available with given id.

    Using load() is faster than merge() and has no side-effects (cascading, etc...)

    0 讨论(0)
  • 2021-02-20 06:01

    Hibernate needs a safe way to determine the state of your object. That's why it's going a long way to make sure you can't mix objects from different sessions (so you can't load the categories at startup and then just use them later).

    The solution is to load the categories at startup, set up a caching provider like ehcache for this class and then use this code:

    Product product = new Product(somename);
    product.setCategory(session.merge(category));
    

    That won't cause any DB round trips if you configure the cache that category instances can't change.

    0 讨论(0)
提交回复
热议问题