gpt4 book ai didi

java - 为什么 hibernate 试图执行格式错误的查询?

转载 作者:行者123 更新时间:2023-12-01 13:43:30 25 4
gpt4 key购买 nike

我在使用 Hibernate 4.2.7.SP1 时遇到问题,我不知道这是误用还是错误。我使用带有注释的 hibernate,我的代码类似于这两个对象:

第一个对象:

@Entity
@Table(name = "TABLE1")
public class FirstObject {
@Id
@GeneratedValue
private Long id; // database id

private SecondOBject secondObject

//Getters, setters and other stuff here.
}

第二个对象:

@Entity
@Table(name = "TABLE2")
public class SecondObject {
@Id
@GeneratedValue
private Long id; // database id.

@ElementCollection
@CollectionTable(name = "T_MAPTABLE")
private Map<String, Integer> iAmAHashmap;

//More maps similar to the previous one, the getters, setters and other stuff.
}

当然,省略了很多代码,因为我认为这与问题无关。

当我执行测试时,我使用“SecondObject”创建一个对象“FirstObject”并尝试使用 hibernate 保存它,我可以看到 hibernate 正在生成以下 sql 代码:

Hibernate:
insert
into
TABLE2

values
( )

如您所见,没有参数,也没有值。因此,启动异常:

 SqlExceptionHelper [main] - [SQLITE_ERROR] SQL error or missing database (near ")": syntax error)

SecondObject 中的 map 具有值(我已经打印了 map 的大小以确保)。但Hibernate不存储它,并尝试在TABLE2中存储空参数。

但是,如果我更改 SecondObject 并添加任何参数(即字符串):

@Entity
@Table(name = "TABLE2")
public class SecondObject {
@Id
@GeneratedValue
private Long id; // database id.

private String dummyText="hello!";

@ElementCollection
@CollectionTable(name = "MAPTABLE")
private Map<String, Integer> iAmAHashmap;

//More maps similar to the previous one, the getters, setters and other stuff.
}

Hibernate生成的代码是:

Hibernate:
insert
into
TABLE2
(dummyText)
values
(?)

至少,没有显示任何错误(但显然 map 没有插入)。

我的 hibernate.cfg.xml 中有:

 ....
<property name="hibernate.hbm2ddl.auto">create-drop</property>
....

执行测试时会自动创建 MAPTABLE。

那么我有两个问题:

为什么 hibernate 尝试执行没有参数和值的查询?为什么我的 map 没有插入? (我在所有只有 map 而没有其他参数的类中都出现此错误)。

最佳答案

不知道你是否省略了,因为 FirstObject<->SecondObject 是与数据库内的外键的关系,你需要用注释来指定。您可以在此处找到不同类型关系的示例,以及示例和进一步说明:http://en.wikibooks.org/wiki/Java_Persistence/Relationships

OneToOne 关系如下所示,以便 JPA 知道外键是什么。

@OneToOne
@JoinColumn(name="ID")
private SecondObject secondObject;

集合也是如此:http://en.wikibooks.org/wiki/Java_Persistence/ElementCollectionCollectionTable-Annotation 有一个属性 joinColumn 来指定外键关系。

关于java - 为什么 hibernate 试图执行格式错误的查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20514218/

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