选择记录,其中id是集合ID之一

时间:2016-02-05 13:44:21

标签: mysql spring hibernate spring-mvc

在spring mvc应用程序中,我有3个数据库表(包括一个映射表)和它们的2个相应的java实体。

实体是: -

public class User {
        private Long id;
        private String userName;

        @ManyToMany(fetch = FetchType.EAGER)  
        @JoinTable(name = "user_location",  
        joinColumns        = {@JoinColumn(name = "user_id", referencedColumnName = "id")},  
        inverseJoinColumns = {@JoinColumn(name = "location_id", referencedColumnName = "id")}  
                )  
        private Set<Location> location;
    }

public class Location {
        private Long id;
        private String locationCode;
    }

三个表是users,location和user_location。

我想选择位置ID等于特定ID的用户。 由于用户可以有多个位置,我不知道如何为此编写一个hibernate查询。我在下面尝试了几个组合,但我要么得到例外,

illegal attempt to dereference collection [{synthetic-alias}{non-qualified-property-ref}] with element property reference [id]

或获取用户和位置对象的列表。我只想要一个用户对象列表。

    来自User的
  • userName =:userName和:locationId in(location.id)
  • 来自用户内部联接user.location loc其中user.userName =:usersName和loc.id =:locationId

更新 我试过了查询,

Query query = getCurrentSession().createQuery("from User user inner join user.location loc where user.userName = :usersName and loc.id = :locationId");  

Hibernate从上面的查询生成以下纯SQL,并返回User和Location对象的列表。例如,如果用户的一个位置与上面的查询匹配,则hibernate返回包含一个User和一个Location对象的列表。

select
        user0_.id as id1_18_0_,
        location2_.id as id1_5_1_,
        user0_.user_name as user_na11_18_0_,
        location2_.location_code as location3_5_1_       
    from
        users user0_ 
    inner join
        user_location location1_ 
            on user0_.id=location1_.user_id 
    inner join
        location location2_ 
            on location1_.location_id=location2_.id 
    where
        user0_.user_name=? 
        and location2_.id=? 

1 个答案:

答案 0 :(得分:1)

您可以尝试使用下一个标准:

Criteria criteria = getCurrentSession().createCriteria(User.class, "u");
criteria.createAlias("location", "loc");
criteria.add(Restrictions.eq("u.userName", "userName");
criteria.add(Restrictions.eq("loc.id", locationId);

List<User> users = criteria.list();

或者您可以尝试HQL类型查询:

TypedQuery<User> query =
    getCurrentSession().createQuery("SELECT User.* FROM User u JOIN user_location ul ON u.id = ul.user_id JOIN Location l ON ul.location_id = l.id WHERE u.userName = :userName AND l.id = :locationId", User.class)
      .setParameter("userName", "userName")
      .setParameter("locationOd", locationId);

List<User> users = query.getResultList();