How to use Hibernate in a multi threaded application?

前端 未结 1 925
無奈伤痛
無奈伤痛 2021-02-04 07:15

I am trying to use Hibernate for a multi threaded application wherein each thread retrieves an object and tries to insert it into a table. My code looks like below. I have loca

1条回答
  •  误落风尘
    2021-02-04 07:43

    With session-objects-per-thread, as long as you are not sharing session objects between multiple threads, you will be fine.

    The error you are receiving is unrelated to your multithreaded usage or your session management. Your usage of session.save() as well as explicitly setting the ID is not quite right.

    Without seeing your mapping for BlogPost its hard to tell, but if you have told Hibernate to use the id field as the primary key, and you are using the native generator for primary keys, the all you need to do is this:

    session.beginTransaction();
    session.persist(b);
    session.flush(); // only needed if flush mode is "manual"
    session.getTransaction().commit();
    

    Hibernate will fill in the ID for you, persist() will cause the insert to happen within the bounds of the transaction (save() does not care about transactions). If your flush mode is not set to manual then you don't need to call flush() as Transaction.commit() will handle that for you.

    Note that with persist(), the BlogPost's ID is not guaranteed to be set until the session is flushed, which is fine for your usage here.

    To handle errors gracefully:

    try {
        session.beginTransaction();
        try {
            session.persist(b);
            session.flush(); // only needed if flush mode is "manual"
            session.getTransaction().commit();
        } catch (Exception x) {
            session.getTransaction().rollback();
            // log the error
        }
    } catch (Exception x) {
        // log the error
    }
    

    By the way, I suggesting making BlogPost.setId() private, or package visible. It is most likely an implementation error if another class sets the ID explicitly (again assuming native generator, and id as primary key).

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