【问题标题】:How to make the hibernate map a created table?如何使休眠映射创建表?
【发布时间】:2014-03-29 10:13:42
【问题描述】:

我尝试为已创建的表仅建模几列。但是Hibernate 无法执行能够为应用程序返回数据的查询。

我在映射创建的表的模型中做这样的事情:

@Column(name="LOCALE_ID")
private String locale;

@Id
@Column(name="ID")
private Long ID;

@Column(name="TITLE")
private String title;

public Location () {}

public Long getID() {
    return ID;
}

public void setID(Long ID) {
    this.ID = ID;
}

public String getLocale() {
    return locale;
}

public void setLocale(String locale) {
    this.locale = locale;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

执行查询的方法如下所示:

String q = "SELECT l.title FROM " + className +
            " l WHERE l.locale = '" + locale + '"';
List<Location> result = null;
try {
    Transaction tx = getSession().beginTransaction();
    result = (List<Location>)session.createQuery(q).list();
    tx.commit();
} catch (Exception ex) {
    ex.printStackTrace();
}
return result;

当我使用正确的参数调用此方法时,没有返回任何内容,但映射表包含可以使用这些参数获取的数据。

我不知道为什么休眠不能处理创建的表。

也许是生成模型的逆向工程,可以提供帮助,但我不知道如何执行此操作。

对此有什么想法吗?

【问题讨论】:

  • 您是否已将 get/set 添加到实体?和@entity?
  • 是的,它有 getter 和 setter
  • 您的查询正在获取 l.title,它是一个字符串 - 您将结果列表转换为 Location 的任何特定原因?
  • 位置是模型类
  • 您的查询语法错误,您需要在末尾多加一个引号,例如 WHERE l.locale = '" + locale + "'"

标签: java hibernate reverse-engineering


【解决方案1】:

您在 try/catch 块中使用一个同名但新的变量来隐藏您的 List 结果,您将查询结果分配给该变量。但是你总是返回分配给 null 的外部变量。

String q = "SELECT l.title FROM " + className +
            " l WHERE l.locale = '" + locale;
List<Location> result = null;
try {
    Transaction tx = getSession().beginTransaction();
    result = (List<Location>)session.createQuery(q).list();
    tx.commit();
} catch (Exception ex) {
    ex.printStackTrace();
}
return result;

可能会更好

【讨论】:

  • 对不起,代码只是我在正文问题中进行了更正
  • 您是否尝试使用String q = "SELECT l FROM " + className + " l WHERE etc. 选择完整的模型类?否则,您不会查询您的模型类,而只是将标题作为字符串(如@Matt 所说)。
  • 我没有尝试过这样的事情,也许你说的这个可以很好,我会尝试
【解决方案2】:

您应该使用查询功能来指定参数,因为这可能是问题所在。 试试这样的

String q = "SELECT l.name FROM yourclassname l WHERE l.locale=:locale";
List<Location> result = null;
try {
    Transaction tx = getSession().beginTransaction();
    session=yourFactory.openSession();
    query=session.createQuery(q);
    query.setParameter("locale",yourLocaleVal);
    result=query.list();
    tx.commit();
} catch (Exception ex) {
    ex.printStackTrace();
}
return result;

【讨论】:

    【解决方案3】:

    执行搜索的最佳方法是在 SELECT 中使用构造函数表达式,见下文:

    String q = "Select new " + className + "(l.ID, l.title, l.locale) From " + className + " l Where l.locale = '" + locale + "'";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多