Four states of JPA objects

Reference: https://blog.csdn.net/mr_wanter/article/details/122807817
Four states of JPA objects: temporary state, free state, persistent state, deletion state (destruction state)

insert image description here

1. Transient state
The entity of the transient state is an ordinary java object, which has nothing to do with the persistence context, and there is no corresponding data in the database.

Second, the free state
When the transaction is committed, the object in the managed state changes to the free state. At this point, the object is no longer in the persistence context, so any modifications to the object will not be synchronized to the database.

3. Managed state
The object returned by the find or persist operation using EntityManager is in the managed state. At this time, the object is already in the persistence context, so any updates to the entity will be synchronized to the database.
The performance is: set the Jpa object, but without saving, the database can also be automatically updated.

4. Deletion state
When the EntityManger is called to delete the entity, the entity object is in the deletion state. Its essence is an object of transient state.

/*
    * JPA四大状态
    * */
    @Test
    public void test_status(){
    
    

        EntityManager entityManager = factory.createEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();

        User user = new User();  //临时状态
        user.setId(6l);//游离状态
        user = entityManager.find(User.class, 5l); //持久状态
        entityManager.remove(user); //删除状态(销毁状态)

        transaction.commit();

    }


    /*
     * JPA四大状态
     * */
    @Test
    public void test_status02(){
    
    

        EntityManager entityManager = factory.createEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();

        User user = entityManager.find(User.class, 1l); //持久状态(持久状态进行修改会同步数据库)
        user.setUsername("admin");

        transaction.commit();

    }

Guess you like

Origin blog.csdn.net/qq_43470725/article/details/128575718
Recommended