gpt4 book ai didi

java - 使用 sql 查询在 hibernate 中创建一个新的对象实例

转载 作者:搜寻专家 更新时间:2023-11-01 02:33:45 24 4
gpt4 key购买 nike

我正在尝试使用查询在 hibernate 中创建一个对象,然后将其保存回代表该类的表中。

hbm.xml 文件摘录:

<class name="MyClass" table="MY_TABLE">
<id column="ID" name="ID">
<generator class="sequence">
<param name="sequence">MY_SEQ</param>
</generator>
</id>
<property column="VAL" name="val" type="string"/>
</class>

<sql-query name="myQuery">
<return class="MyClass"/>
SELECT MY_SEQ.nextval ID, 'something' VAL from DUAL
</sql-query>

测试用例的代码片段:

MyClass myClass = (MyClass) session.getNamedQuery("myQuery").list().get(0);
Transaction t = session.beginTransaction();
session.save(myClass);
t.commit();

我的目标是现在应该在表 MY_TABLE 中有一条新记录,但是没有发生插入,我认为这是因为 Hibernate 不知道该实例尚未在数据库中持久化。

我尝试将查询更改为:

SELECT NULL ID, 'something' VAL from DUAL

但这会导致 Hibernate 不实例化对象。

那么我如何从与类的持久化实例无关的查询中创建一个新的对象实例,并使用它来创建一个持久化实例?

最佳答案

更新:我测试了下面建议的方法,但我无法让它适用于这种特定情况,Hibernate 希望您为所有属性选择列,而我们绝对不需要 id。但是,使用 ResultTransformer做了工作:

16.1.5. Returning non-managed entities

It is possible to apply a ResultTransformer to native SQL queries, allowing it to return non-managed entities.

sess.createSQLQuery("SELECT NAME, BIRTHDATE FROM CATS")
.setResultTransformer(Transformers.aliasToBean(CatDTO.class))

This query specified:

  • the SQL query string
  • a result transformer

The above query will return a list of CatDTO which has been instantiated and injected the values of NAME and BIRTHNAME into its corresponding properties or fields.

文档提到返回非托管实体,但它也适用于实体(没有理由它不起作用),我可以 persist transient 实体成功。

另见

为了清楚起见,我将保留最初的答案。


<罢工>也许以下内容会有所帮助:

16.1.2. Entity queries

The above queries were all about returning scalar values, basically returning the "raw" values from the resultset. The following shows how to get entity objects from a native sql query via addEntity().

sess.createSQLQuery("SELECT * FROM CATS").addEntity(Cat.class);
sess.createSQLQuery("SELECT ID, NAME, BIRTHDATE FROM CATS").addEntity(Cat.class);

This query specified:

  • the SQL query string
  • the entity returned by the query

Assuming that Cat is mapped as a class with the columns ID, NAME and BIRTHDATE the above queries will both return a List where each element is a Cat entity.

If the entity is mapped with a many-to-one to another entity it is required to also return this when performing the native query, otherwise a database specific "column not found" error will occur. The additional columns will automatically be returned when using the * notation, but we prefer to be explicit as in the following example for a many-to-one to a Dog:

sess.createSQLQuery("SELECT ID, NAME, BIRTHDATE, DOG_ID FROM CATS").addEntity(Cat.class);

This will allow cat.getDog() to function properly.

但我认为如果你想保存它并希望Hibernate执行插入,你不应该设置ID。

关于java - 使用 sql 查询在 hibernate 中创建一个新的对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3266492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com