带有映射实体的HQL查询

时间:2013-12-09 19:33:51

标签: sql spring hibernate hql

@Entity(name = "locations")
@Table(name="locations")
public class Location {

 @Id
 @GeneratedValue
 @Column(name="id") 
 private long id;

 @Column(name="name") 
 @NotEmpty(message="El Nombre es obligatorio") @Size(min=3, max=150, message="El Nombre debe tener entre 3 y 150 caracteres")
 private String name;

 @OneToMany(mappedBy="location")
 private List<SportEvent> sportevents;

 }

@Entity(name = "sports")
@Table(name = "sports")
public class Sport {

 @Id
 @GeneratedValue
 @Column(name="id") 
 private long id;

 @Column(name="name") 
 @NotEmpty(message="El Nombre es obligatorio") @Size(min=3, max=150, message="El Nombre debe tener entre 3 y 150 caracteres")
 private String name; 

 @Column(name="active")
 private Boolean active;

 @OneToMany(mappedBy="sport") //nombre de la varible de la otra entidad
 private Set<SportEvent> sportevents;

}


@Entity(name = "sport_events")
@Table(name="sport_events")
public class SportEvent {

 @Id
 @GeneratedValue
 @Column(name="id") 
 private long id;

 @Column(name="name") 
 @NotEmpty(message="El Nombre es obligatorio") @Size(min=3, max=150, message="El Nombre debe tener entre 3 y 150 caracteres")
 private String name; 

 @ManyToOne
 @JoinColumn(name="sport_id")
 private Sport sport;

 @ManyToOne
 @JoinColumn(name="location_id")
 private Location location;

 }

查询:

 locations = (List<Location>) s.createQuery("SELECT DISTINCT l " +
                                           "FROM locations l " +
                                           "JOIN l.sportevents AS lse " +
                                           "WHERE lse.sport.id = :id")
                                           .setLong("id", sportId)
                                           .list();

我希望通过运动菜单过滤体育赛事的respetivos位置 通过以下查询,我得到了体育赛事的位置,但忽略了WHERE id sport的条件。

如果它已正确映射到已经有体育赛事的访问位置,我只需要进行JOIN条件运动但不起作用。

在听证会上,我打印得很好:

<c:forEach var="location" items="${locations}">
    <li>
        <label class="tree-toggle nav-header"><i class="icon-hand-right"></i><a href="#">${location.name}</a></label>
        <ul class="nav nav-list tree hide">
            <c:forEach var="sportevent" items="${location.sportevents}">
                <li><a href="#">${sportevent.name}</a></li>
            </c:forEach>
        </ul>   
    </li>
    <li class="divider"></li>
</c:forEach>

在我的数据库中,我有:

的运动: ID名 1-SPORT1 2- SPORT2 3- sport3

位置 ID名 1-LOCATION1 2- LOCATION2

活动 ID-名称sport_id-LOCATION_ID 1-event1-2-1 2- event2-2-1 3 event3-1-2 4- event4-1-2 5 event5-3-1 6- event6-3-1

为各自的赛事添加位置但属于特定运动。使用当前查询,我只按位置获取事件。在我的网站上,我在所选运动的菜单中,我想要有运动项目的地点。

0 个答案:

没有答案