2016-06-24 3 views

答えて

1

エンティティの分離とは、休止状態がエンティティへのアクセスをもう持たないことを意味します。以下の例を参照してください。

//Thid is where the entity is in transient State (Ther data is not saved, but initialized) 
User user = new user 
user.setName("User1"); 
Configuration configuration = new Configuration().configure(); 
    StandardServiceRegistryBuilder builder = (StandardServiceRegistryBuilder) new StandardServiceRegistryBuilder() 
      .applySettings(configuration.getProperties()); 
    ServiceRegistry serviceRegistry = builder.build(); 
    SessionFactory factory = configuration.buildSessionFactory(serviceRegistry); 

    Session session = factory.openSession(); 
    Transaction tx = session.beginTransaction(); 
    user.setUserName("Hello There");//Here the data is in persistent state 
    session.save(user); 
    user.setUserName("Hello There Again");//Here also the data is in persistent state 
      user.setUserName("Hello There Again for second time");//Here also the data is in persistent state, but the hibernate will take the last update, if you see the query in log/console, you will find only one update query. 
    tx.commit(); 
    session.close(); 
    user.setUserName("Hello Again Final");//Since the session is closed, the data is not persisted, Here the entity is detached 
    factory.close(); 
    StandardServiceRegistryBuilder.destroy(serviceRegistry); 

データベースのクローズ後にエンティティの分離が発生するのは、通常はsession.close()を実行した後です。ワークフロー上の

詳しい情報はこちらをhttps://javabrains.io/courses/hibernate_run/lessons/Understanding-State-Changes

+0

あなたは絶対に正しいですが、detach()と呼ばれるメソッドがあり、それをデタッチするメソッドを明示的に呼び出すことはできますか?私はデタッチエンティティの必要性を尋ねていますか? –

関連する問題