2013-06-18 57 views
1

我有兩個表:搜索在鍵值表休眠(或SQL查詢)

  • 內容(ID,數據,標題,大小)
  • ContentProperties(ID,鍵,值,fk_content_id)

每個內容記錄可以有許多屬性(一對多)。我希望使用Hibernate與這些條件(它的僞代碼)檢索內容記錄:

(content.title == "article") 
AND 
if(content.contentProperties.key == "author") 
{ 
    content.contentProperties.value = "david" 
} 
AND 
if(content.contentProperties.key == "pages") 
{ 
    content.content.contentProperties.value <= "150" 
    content.content.contentProperties.value >= "050" 
} 

什麼是它的SQL查詢?我如何用hibernate api做到這一點? 在此先感謝。

回答

1

我創建了Restrictions.sqlRestriction鍵值標準:

private Criterion createKeyValueSqlCriteria(String key, String operator, Object value) 
{ 
    if(operator.equals("like")) 
    { 
     value = "%" + ((String)value) + "%"; 
    } 
    Object[] valueArray = {key, value}; 
    Type[] typeArray = {StringType.INSTANCE, getValueType(value)}; 

    String query = "exists (select 1 from CONTENT_PROPERTY cp " + 
        "where cp.FK_CONTENT_ID = {alias}.CONTENT_ID " + 
        "and cp.KEY= ? and cp.VALUE " + operator + " ?)"; 

    Criterion criterion = Restrictions.sqlRestriction(query,valueArray,typeArray); 
    return criterion; 
} 

private Type getValueType(Object value) 
{ 
    if(value instanceof String) 
    { 
     return StringType.INSTANCE; 
    } 
    else if (value instanceof Long) 
    { 
     return LongType.INSTANCE; 
    } 
    else if (value instanceof Double) 
    { 
     return DoubleType.INSTANCE; 
    } 
    else if (value instanceof Boolean) 
    { 
     return BooleanType.INSTANCE; 
    } 
    else if (value instanceof Date) 
    { 
     return DateType.INSTANCE; 
    } 
    else 
    { 
     return null; 
    } 
}