How to make Hibernate ignore a method?

前端 未结 3 1583
再見小時候
再見小時候 2021-01-03 22:09

This question is essentially the opposite of this one.

I have a method like so:

public boolean isVacant() {
    return getEmployeeNum() != null &         


        
相关标签:
3条回答
  • 2021-01-03 22:47

    Many frameworks (like Hibernate and Drools) are smart enough understand that Boolean variables need to be accessed by "is" instead of "get". But they don't always understand perfectly, and that is when "interesting" problems can develop. Or, worse yet, the different frameworks interpret the methods slightly differently, and they are supposed to work together.

    BTW, the @Transient solution is not guaranteed to solve all your problems. Most notably, say that you are adding it to a toString() that returns a huge and complex object. You might be getting a stack overflow not because the method is huge and complex, or even because all the sub-obejcts have their own toString() methods, but because your structure has circular structures. That is what causes the stack overflows.

    0 讨论(0)
  • 2021-01-03 22:56

    Add @Transient to the method then Hibernate should ignore it.

    To quote the Hibernate Documentation:

    Every non static non transient property (field or method depending on the access type) of an entity is considered persistent, unless you annotate it as @Transient.

    0 讨论(0)
  • 2021-01-03 22:58

    RNJ is correct, but I might add why this happens:

    I'm guessing that you have annotated the getters of your persistent class. The prefixes used by java beans are "set" and "get", which are used do read and write to variables, but there is also the prefix "is", which is used for boolean values (instead of "get"). When Hibernate sees your getter-annotated persistent class, and finds a method "isVacant", it assumes that there is a property "vacant", and assumes that there is a "set"-method as well.

    So, to fix it, you could either add the @Transient annotation, or you could change the name of your method to something that doesn't start with "is". I don't think this would be a problem if your class was annotated on the fields, instead of the get-methods.

    0 讨论(0)
提交回复
热议问题