강의 출처- 인프런 김영한 강사님
https://www.inflearn.com/course/ORM-JPA-Basic

Persistence Context

When it is created

for every single request, jpa makes persistence context and at the end of the business logic, this persistence context is destroyed.


1st Cache of Persistence Context

In persistence context, the data is cached. And this is called 1st cache.

Example code (Ensurance of Entity's Equality)
with scope of the same transaction

 Member findMember1 = em.find(Member.class, 1L);
            Member findMember2 = em.find(Member.class, 1L);
            System.out.println("findMember1 equals findMember2 ? " + (findMember1 == findMember2));
            // Result: True

this is possible due to the persistence context.

Benefit of 1st Cache

In case the business logic is really complicated, we can get some performance benefit by this 1st cache, although it is rare case. And this is not useful as such in the practical case because this 1st cache is narrow-wide cache by the mechanism.


Flush

em.persist(member1);
em.persist(member2);
System.out.println("============================"); 
// not execute query before transaction commit.

tx.commit();
// all queries executed.

we can set this queries batch size inside persistence.xml file.


Batch size config in persistence.xml

<property name="hibernate.jdbc.batch_size" value="10"/>

configure the query size of behind write.

Detecting Change

Member findMember = em.find(Member.class, 150L);
findMember.setName("I changed this to B"); // original name: A 
// no need to 'em.persist(findMember)'

No need to 'em.persist(findMember)'

It automatically detects the change of any property(compared with the first snap shot inside Persistence Context) and executes update query. Thus, we can write treat them as if they're like "Java Collections"

more detailed case

Member member = new Member(100L, "new");
            em.persist(member);

            member.setName("new new");

            System.out.println("============================");
============================
Hibernate: 
    /* insert hellojpa.Member
        */ insert 
        into
            Member
            (name, id) 
        values
            (?, ?)
Hibernate: 
    /* update
        hellojpa.Member */ update
            Member 
        set
            name=? 
        where
            id=?

In case like above, insert and update queries are executed in order after the transaction is commited.

profile
No pleasure, No gain

0개의 댓글

Powered by GraphCDN, the GraphQL CDN