使用hibernate(或SQL查询)在键值表中搜索

时间:2013-06-18 14:59:15

标签: java sql hibernate hibernate-criteria

我有两张桌子:

  • 内容(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 个答案:

答案 0 :(得分: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;
    }
}