![]() ![]() The problem with this is that once it runs this query, it will return multiple rows if the User it finds has logged into the system more than once.Īgain, it does this because it's an optional (left) join. So in the code directly above, we are querying the database for Users that have a username matching the String that's being passed in. Return session.createCriteria(User.class).add(Restrictions.eq("username", username)).list() Session session = sessionFactory.getCurrentSession() public List getUserByUsername (String username) This.loggedIn = optional=true, User getUser()Īnd then we have the entry in a DAO class that will query for Users by passing in a username. Public void setLoginHistoryId(Long loginHistoryId) Public void setLoginHistory(List loginHistory) This.password = mappedBy="user", fetch=FetchType.EAGER) Below you'll see an outline of the optional one-to-many join between the User class and the LoginHistory class. So here's an example of the problem in action. ![]() Make use of Distinct Root Entity Results Transformer.The ball is in your court to tell Hibernate what to do with records it has retrieved. So because of this, Hibernate doesn't massage the data for you, it just returns exactly what it got from the database. So what happens when you run a query that joins to the LoginHistory table? Well it will return as many rows as there are entries for that User in the LoginHistory table. ![]() You'll have a situation where you have many records in the LoginHistory table. And let's say our user has logged in many times. When you have a base object, like say User and it joins to another table/object in an optional One-to-Many or optional Many-to-Many format, then you may get duplicates.Ĭonsider this scenario… A User objects joins to the LoginHistory object, which keeps track of all the times a particular User has logged into the system. You see the problem is typically caused by having left joins (or optional joins) in your objects. If you're executing a query and finding that you have a bunch of duplicate records and haven't a clue why, then you're in the right place. This problem was the bane of my existence when I first started using Hibernate because I had no idea where the problem was coming from. How to Avoid Duplicate Records from Hibernate Queries If you haven't had the pleasure of going through all the tutorials, I'd suggest going to this page and having a flip through all the topics. We've covered a lot of topics on Hibernate already on this blog in a nice sequential format. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |