Java Hibernate:不同的属性集函数行为取决于谁调用它 [英] Java Hibernate: Different property set function behavior depending on who is calling it

查看:52
本文介绍了Java Hibernate:不同的属性集函数行为取决于谁调用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我在Hibernate处理的类中为给定属性定义了一组get和set函数. set函数是一个公共函数,可以由Hibernate的机制以及正常的代码流调用.

Let's say I define a set of get and set functions for a given property in a class that gets handled by Hibernate. The set function is a public one which may be called by Hibernate's mechanisms as well as normal flow of code.

如果set函数是由Hibernate调用的,则应只设置该字段的值.如果该集合是由另一个来源调用的,则它还应该相应地更新其他字段.

If the set function is called by Hibernate, it should just set the field's value. If the set is called by another source, it should also update additional fields accordingly.

代码中是否存在区分两种情况的方法?还是有更好的做法来处理这种情况?

Is there a way in code to differentiate between the two situations? Or, is there a better practice for handling this situation?

推荐答案

最简单的处理方法是将Hibernate配置为直接访问字段,而不是通过方法.在这种情况下,您可以在getter和setter中实现任何类型的逻辑,而Hibernate不会触发它.

The easiest way to handle it is to configure Hibernate to access fields directly rather than through the methods. In that case you can implement any kind of logic in your getters and setters, and Hibernate won't trigger it.

如果您使用基于注释的方法,则可以通过在字段上放置注释来配置此行为.

If you use annotation-based approach, this behaviour can be configured by placing annotation on fields.

如果必须使用属性访问器,则可以创建两个由相同字段支持的属性-一个用于Hibernate(可以是非public),另一个用于其他代码(应标注为使Hibernate忽略它.)

If you have to use property accessors, you can create two properties backed by the same field - one for Hibernate (it can be non-public), and another one for other code (it should be annotated as @Transient to make Hibernate ignore it).

这篇关于Java Hibernate:不同的属性集函数行为取决于谁调用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆