# Unable to get Updated data from View's Entity

**URL:** https://discourse.hibernate.org/t/unable-to-get-updated-data-from-views-entity/1198
**Category:** Hibernate ORM
**Created:** [August 8, 2018, 11:55am UTC](https://discourse.hibernate.org/t/unable-to-get-updated-data-from-views-entity/1198 "2018-08-08T11:55:55Z")
**Posts on this page:** 8
**Page:** 1

<div class="post-metadata">

### Author: ![dhiraj07](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/dhiraj07/32/175_2.png) [@dhiraj07](https://discourse.hibernate.org/u/dhiraj07)
#### Post date: [August 8, 2018, 11:55am UTC](https://discourse.hibernate.org/t/unable-to-get-updated-data-from-views-entity/1198/1 "2018-08-08T11:55:55Z")

</div>

Hii,

I use the MYSQL view for Complex Queries

When I update the Original Entity with merge() method.

then the view Entity not reflect the updated Data simultaneously.

---

<div class="post-metadata">

### Author: ![vlad](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/vlad/32/658_2.png) [@vlad](https://discourse.hibernate.org/u/vlad)
#### Post date: [August 8, 2018, 12:07pm UTC](https://discourse.hibernate.org/t/unable-to-get-updated-data-from-views-entity/1198/2 "2018-08-08T12:07:26Z")

</div>

Show us some code to understand what you are doing.

---

<div class="post-metadata">

### Author: ![dhiraj07](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/dhiraj07/32/175_2.png) [@dhiraj07](https://discourse.hibernate.org/u/dhiraj07)
#### Post date: [August 14, 2018, 11:21am UTC](https://discourse.hibernate.org/t/unable-to-get-updated-data-from-views-entity/1198/3 "2018-08-14T11:21:57Z")

</div>

Dear,

I am using method to save:

```auto
public Payload save(Payload payload)
	{
		MobiloitteEntityManager mobiloitteEntityManager = null;
		try
		{
			// mobiloitteEntityManager = getEntityManager(payload.getTransferObjectMap());
			BaseEntity[] be = (BaseEntity[]) payload.getTransferObjectMap().get(SAVE_ENTITIES);
			BaseEntity[] savedBE = new BaseEntity[be.length];
			boolean keyFlag = false;
			String key = (String) payload.getTransferObjectMap().get(TRANSACTION_KEY);

			if(key == null)
			{
				key = startTransaction();
				keyFlag = true;
			}
			if(be != null)
			{
				int count = 0;
				for(BaseEntity obj:be)
				{
					IntfCacheManager intfCacheManager = DefaultCacheManagerImpl.getInstance();
					// MobiloitteEntityManager mobiloitteEM = (MobiloitteEntityManager)intfCacheManager.pull(key);
					mobiloitteEntityManager = (MobiloitteEntityManager)intfCacheManager.pull(key);
					// mobiloitteEM.getEntityManager().persist(obj);
					obj = mobiloitteEntityManager.getEntityManager().merge(obj);
					mobiloitteEntityManager.getEntityManager().flush();
                                        
/
					mobiloitteEntityManager.getEntityManager().refresh(obj);
					
					//TO Evict Related View of Related View 
					EvictUtil.evictMethod(obj.getClass().getName(), mobiloitteEntityManager.getEntityManager());
					savedBE[count] = obj;
					count++;
				}
			}
			if(keyFlag)
			{
				commitTransaction(key);
				payload.put(SAVE_ENTITIES,savedBE);
			}
			// payload.getTransferObjectMap().put("dbprocess",ConstantsShared.SUCCESS);
			// payload.setEvent(payload.getEventInternal());

			// payload = PayloadResponse.getPayloadResponse(payload,"entityData"); //TODO set entity data to transfer object map
		}
		catch(Exception e)
		{
			e.printStackTrace();
			mobiloitteEntityManager.getEntityManager().getTransaction().rollback();
			payload.getTransferObjectMap().put("dbprocess",ConstantsShared.FAILURE);
		}
		return payload;
	}

```

As I found a link to Evict Method:

> <https://stackoverflow.com/questions/13258976/how-to-refresh-jpa-entities-when-backend-database-changes-asynchronously>

TO Evict Related View of Related View  
EvictUtil.evictMethod(obj.getClass().getName(), mobiloitteEntityManager.getEntityManager());  
With the Help of this Method

after I save the Entity and Trying to Get Data from View’s Entity  
When I restart the database or Server then it reflect on getting this Entity

When I run the Genereted SQL Query form console and run in mysql workbench  
then it reflect the expected Result

---

<div class="post-metadata">

### Author: ![vlad](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/vlad/32/658_2.png) [@vlad](https://discourse.hibernate.org/u/vlad)
#### Post date: [August 15, 2018, 5:16am UTC](https://discourse.hibernate.org/t/unable-to-get-updated-data-from-views-entity/1198/4 "2018-08-15T05:16:59Z")

</div>

You don’t need that:

```auto
 obj = mobiloitteEntityManager.getEntityManager().merge(obj);
mobiloitteEntityManager.getEntityManager().flush();
mobiloitteEntityManager.getEntityManager().refresh(obj);

```

Just use this instead:

```auto
 obj = mobiloitteEntityManager.getEntityManager().merge(obj);

```

More, the proper way to evict a view is to use the `@Syncrhonize` annotation as explained in the [User Guide](http://docs.jboss.org/hibernate/orm/5.3/userguide/html_single/Hibernate_User_Guide.html#entity-sql-query-mapping).

---

<div class="post-metadata">

### Author: ![dhiraj07](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/dhiraj07/32/175_2.png) [@dhiraj07](https://discourse.hibernate.org/u/dhiraj07)
#### Post date: [August 16, 2018, 5:26am UTC](https://discourse.hibernate.org/t/unable-to-get-updated-data-from-views-entity/1198/5 "2018-08-16T05:26:27Z")

</div>

I used @synchronise annotation on Related View Entity

```auto
@Entity
@Table(name="user_detail")
@NamedQueries
({
	@NamedQuery(name="UserDetail.findAll", query="SELECT u FROM UserDetail u")	
})
public class UserDetail extends BaseEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(name="user_id")
	private Long userId;

	private String address;
 }

```

```auto
@Entity
@Table(name="user_login_detail")
@NamedQuery(name="UserLoginDetail.findAll", query="SELECT u FROM UserLoginDetail u")
public class UserLoginDetail extends BaseEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(name="LOGIN_ID")
	private Long loginId;
}

//View Entity
@Entity
@Table(name="getusers")
@NamedQueries({
	//for list
	@NamedQuery(name="Getuser.findAll", query="SELECT g FROM Getuser g where g.status<>'DELETE'"),
	@NamedQuery(name="Getuser.findByRole", query="SELECT g FROM Getuser g where g.role =:role and g.status<>'DELETE' order by g.userId ASC")
})
@Synchronize( {"user_detail", "user_login_detail"} )
public class Getuser extends BaseEntity implements Serializable {
	
	private static final long serialVersionUID = 1L;

	private Long creationTime;

}

```

But Still Not Reflect Updated Result

---

<div class="post-metadata">

### Author: ![vlad](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/vlad/32/658_2.png) [@vlad](https://discourse.hibernate.org/u/vlad)
#### Post date: [August 16, 2018, 5:47am UTC](https://discourse.hibernate.org/t/unable-to-get-updated-data-from-views-entity/1198/6 "2018-08-16T05:47:28Z")

</div>

If the `Getuser` entity is already managed and stored in the Hibernate `Session`, you need to call refresh.

Check out the [User Guide](http://docs.jboss.org/hibernate/orm/5.3/userguide/html_single/Hibernate_User_Guide.html#entity-sql-query-mapping) for more details about what’s the purpose of `@Synchronize` and why you also need refresh.

---

<div class="post-metadata">

### Author: ![dhiraj07](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/dhiraj07/32/175_2.png) [@dhiraj07](https://discourse.hibernate.org/u/dhiraj07)
#### Post date: [August 18, 2018, 5:11am UTC](https://discourse.hibernate.org/t/unable-to-get-updated-data-from-views-entity/1198/7 "2018-08-18T05:11:37Z")

</div>

Thanks for your Suggestion.  
It worked after calling the refresh method on View’s Entity.

Is there any possibility to call the refresh method automatically after every save method without calling Related view’s Entity.  
like for Second Level cache evict method  
mobiloitteEntityManager.getEntityManager().getEntityManagerFactory().getCache().evict(Getuser.class);  
OR  
mobiloitteEntityManager.getEntityManager().getEntityManagerFactory().getCache().evictAll();

---

<div class="post-metadata">

### Author: ![vlad](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/vlad/32/658_2.png) [@vlad](https://discourse.hibernate.org/u/vlad)
#### Post date: [August 18, 2018, 5:43am UTC](https://discourse.hibernate.org/t/unable-to-get-updated-data-from-views-entity/1198/8 "2018-08-18T05:43:02Z")

</div>

That would not necessarily guarantee that you are using the latest data. Maybe some other Session modifies the same data as your current cached View result.

More, why do you use the View in the first place? Wouldn’t a query returning a list of DTOs work better?

Views are best when Hibernate can actually update the content of the View. Otherwise, a DTO projection is much more flexible.
