Get the App
SLTechnology News&Howtos  ›  Development  › 

How to get Hibernate Association relationship

Shulou Source: shulou.com Published: 2022-06-02 09:29:16 09月15日 Update

This article mainly introduces how to obtain the Hibernate relationship, which has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, let the editor take you to understand it.

Gets the pojo of the Hibernate association relationship. I mean, for example, a User (user) has an attribute Unit (unit) of many-to-one, but sometimes the Unit attribute of some users is empty. If you query users by unit, those users whose unit is null will be left out. How to call it? This was supposed to be very simple, but I took it for granted that I used Restriction.eq, but I couldn't. Later, I read the manual and found that I should use Restrictions.isNul.

Here is the Test code:

Public void getUsersWhosUnitIsNullByRestrictionsEqNullUnit () {DetachedCriteria dc = DetachedCriteria.forClass (User.class); dc.add (Restrictions.eq ("unit", null)); Criteria cri = dc.getExecutableCriteria (session); log.debug ("getUsersWhosUnitIsNullByRestrictionsEqNullUnit ():" + cri.list (). Size ()) } / * * / / * in order to obtain a user whose unit is null, an error will be reported if a Unit instance with id of null is passed, which cannot be translated into SQL * error type: org.hibernate.TransientObjectException * this is not the result we expected * / @ Ignore @ Test (expected=TransientObjectException.class) public void getUsersWhosUnitIsNullByRestrictionsEqUnitNullId () {Unit unit = new Unit (); log.debug (unit.getId ()) DetachedCriteria dc = DetachedCriteria.forClass (User.class); dc.add (Restrictions.eq ("unit", unit)); Criteria cri = dc.getExecutableCriteria (session); log.debug ("getUsersWhosUnitIsNull ():" + cri.list (). Size ()) } / * * / / * the correct way to get a user whose unit is null is to use the Restrictions.isNull method * because the SQL executed is: (select *) from USER_INF this_ where this_.UNIT_ID is null * this is the result we want * / @ Test public void getUsersWhosUnitIsNullByRestrictionsIsNull () {DetachedCriteria dc = DetachedCriteria.forClass (User.class); dc.add (Restrictions.isNull ("unit")) Criteria cri = dc.getExecutableCriteria (session); log.debug ("getUsersWhosUnitIsNullByRestrictionsIsNull ():" + cri.list (). Size ());} Thank you for reading this article carefully. I hope the article "how to obtain Hibernate relationships" shared by the editor will be helpful to you. At the same time, I hope you will support us, pay attention to the industry information channel, and more related knowledge is waiting for you to learn!

Tags: Users articles associations units properties methods results no take it for granted code value interest at the same time examples manuals times more friends knowledge types Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Apple Xiaomi NVidia Docker