2012-02-02 132 views
1

是否有可能在沒有外鍵的2個桌子之間進行連接?HQL加入沒有外鍵在桌子上

編輯:好的,我確信這是可能的,但我不完全確定如何去做。

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[]>(); 

,但我得到的錯誤:

Semantic exception was unhandled by user code Path expected for join!

[select b from Booking as b inner join BookingLocation as bl on b.bookingID = bl.bookingID]

我採取這種做法,因爲我不能輕易地建立映射這兩個表之間的關係。你需要有一個關係才能進行加入?

回答

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>(); 
3

by 2 tables你是指兩個映射到2個表的正確的類嗎?在這種情況下,你可以使用類(比方說兩個類的Foo映射到一些表&吧)如下:

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[]>(); 

希望這是你想要的。

+0

感謝您的回答,我試圖使用您的建議,但我一直無法弄清楚語法。我編輯了我原來的文章,你介意重寫你的示例代碼嗎? – iKode 2012-02-03 09:35:36