Involving save method and caching mechanism in hibernacle

It is very interesting for hibernacle to add methods and caches. I encountered it in a project some time ago. Look at the columns below:

 

@Primary
@Repository("baseDao")
public class BaseDaoImpl<T> implements BaseDao<T> {

	@Autowired
	private SessionFactory sessionFactory;

	private SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();//Get the current session
	}

	public Serializable save(T t,Puser puser) {
		Serializable s = this.getCurrentSession().save(this.getCurrentSession().merge(t));
		setLog(t, "Add", puser);
		return s;
	}

	public void update(T t,Puser puser) {
		this.getCurrentSession().update(this.getCurrentSession().merge(t));
		setLog(t, "更新",puser);
	}

 Serializable s = this.getCurrentSession().save(this.getCurrentSession().merge(t));

Observe this sentence, there is a merge method in the save method, this method is to find from the hibernate cache (search according to the primary key of the object), if it is found in the cache, replace the object in the cache and save it to the database, so that In one case, even if the primary keys of the two objects are the same, a primary key conflict exception will not be reported, it is just a replacement.

 

What if you want the database's primary key constraints to take effect?

Serializable s = this.getCurrentSession().save(t);

Put it directly into t, if so, hibernate will not go to the cache to find it, but directly store it in the database.

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326613113&siteId=291194637