Why does load () work the same as get () in Hibernate?

I am trying to update an object field this way:

    SessionFactory factory = HibernateUtil.getSessionFactory();
    Session session = factory.openSession();
    session.beginTransaction();
    User user = session.load(User.class, 4);
    user.setName("Bober11");
    session.getTransaction().commit();
    session.close();

      

I thought that in this case Hibernate would update the row in the table without clicking it (I mean, no selection), however I saw in the console that Hibernate is making a selection:

Hibernate: select user0_.id as id1_1_0_, user0_.email as email2_1_0_, user0_.name as name3_1_0_, user0_.phone as phone4_1_0_ from User user0_ where user0_.id=?
Hibernate: update User set email=?, name=?, phone=? where id=?

      

those. looks like if i used get ().

Why is this happening? Can I update and insert without choice? and without using direct SQL queries.

+3


source to share


2 answers


When you call session.load(User.class, 4)

, hibernate creates a proxy object for the User object without calling db (no selection) and connects id = 4 to the proxy object. It's just a proxy with an identifier and information about the session, object type, id ... The
real coll to db only happens when the proxy methods are called - it loads / fetches a request that loads the real object from the DB. In your case, you are calling setName("Bober11")

on a proxy object, and you see a select query as a result.

If you need to update user information by id without additional hibernation, do so with an HQL update query:



    String updateUserHql = "update User set name = :newName where id= :userId";
    Query query = session.createQuery(hql);
    query.setLong("userId",userId); // userID= 4
    query.setLong("newName ",newUserName);//Bober11
    query.executeUpdate();

      

0


source


load()

returns a proxy object without hitting the database. only when you change your field the object is fetched from the database.

get()

returns the actual object and therefore always ends up in the database. If you want to update the table without any choice, you will need to create an HQL query like this:



session.createQuery("UPDATE MY_TABLE SET MY_FIELD = 'MY_VALUE'").executeUpdate();

      

0


source







All Articles