没有外键的HQL连接在表上

时间:2012-02-02 18:52:23

标签: hibernate nhibernate

是否可以在没有外键的2个表之间进行连接?

编辑:好的,我确信这是可能的,但我还不完全确定如何做到这一点。

public class Booking
{
    public virtual int Id { get; set; }
    public virtual Int32 bookingID { get; set; }
    public virtual Int32 bookingAdminID { get; set; 
}

public class BookingLocation
{
    public virtual int Id { get; set; }
    public virtual Int32 bookingID { get; set; }
    public virtual Int32 locationID { get; set; } 
}

映射

 public BookingMap()
 {
    Table("Bookings");

    Id(x => x.Id).Column("ID");
    Map(x => x.bookingID).Column("BookingID");
    Map(x => x.bookingAdminID).Column("BookingAdminID");
 }

public class BookingLocation
{
    public virtual int Id { get; set; }
    public virtual Int32 bookingID { get; set; }
    public virtual Int32 locationID { get; set; } 
 }

我需要在上面两个表的bookingID上做一个简单的内部联接。我该怎么做?

我试过了:

var hql = "select b from Booking as b inner join BookingLocation as bl on b.bookingID =   bl.bookingID";
var bookings = session.CreateQuery(hql).List<object[]>(); 

但是我收到了错误:

  

语义异常未被加入期望的用户代码路径处理!

     

[从预订中选择b作为b内部加入BookingLocation为bl on   b.bookingID = bl.bookingID]

我正在采用这种方法,因为我无法在映射中轻松地在这两个表之间建立关系。您是否需要建立关系才能加入?

2 个答案:

答案 0 :(得分:3)

2个表是指两个映射到2个表的类是否正确?在这种情况下,你可以使用类(比如映射到某些表的两个类Foo&amp; Bar),如下所示:

session.CreateQuery("select * from A as a, B as b 
where a.Prop1=:value1 and b.Prop2=:value2" //conditions if any)
.SetString("value1",val1)
.SetString("value2",val2)
.List<object[]>();

希望这就是你想要的。

答案 1 :(得分:0)

我能够通过向我的实体添加关系来解决这个问题:

 public class Booking
 {
     public virtual int Id { get; set; }
     public virtual Int32 bookingID { get; set; }
     public virtual Int32 bookingAdminID { get; set; }


     public virtual IList<BookingLocation> BookingLocations { get; set; }

     public Booking()
     {
         BookingLocations = new List<BookingLocation>();
     }
 }

public class BookingLocation
{
    public virtual int Id { get; set; }
    public virtual Int32 bookingID { get; set; }
    public virtual Int32 locationID { get; set; } 
    public virtual Booking Booking { get; set; }
}

即使他们没有外键,我也可以像这样进行连接:

var bookings = session.CreateCriteria<Booking>("p")
                              .CreateCriteria("p.BookingLocations", JoinType.InnerJoin)
                              .SetMaxResults(30) 
                              .List<Booking>();