[Hibernate]"column ambiguously defined"异常

使用Hibernate的NativeSQL写了一个查询语句,但是后台报了SQL语法错误,具体报错如下:

[2012-08-08 12:55:00] ERROR  -> ORA-00918: column ambiguously defined
[2012-08-08 12:55:00] ERROR  -> org.hibernate.exception.SQLGrammarException: could not execute query

原因一:

如果2张表包含相同的字段,则对着同一个字段的操作如果不加上表名就会报此异常,如:

Student表:

id

name

1

student1

2

student2

CREATE TABLE `Student` (
	`id` int(11) NOT NULL,
	`name` char(20) NOT NULL,
	PRIMARY KEY (`id`)
)

Teacher表:

id

name

studentid

1

teacher

1

CREATE TABLE `Teacher` (
	`id` int(11) NOT NULL,
	`name` char(20) NOT NULL,
	`studentid` int(11) DEFAULT NULL,
	PRIMARY KEY (`id`),
	CONSTRAINT `FK_STUDENTID` FOREIGN KEY (`studentid`) REFERENCES `student` (`id`)
)

则使用如下的sql查询就会报上面的异常:

select name from Teacher t LEFT OUTER JOIN Student s on t.studentid = s.id

SQL语句本身就是有问题的,事实上数据库不知道SQL中的name到底是Student表中的name字段还是Teacher表中的name字段

 

原因二:

还有一种情况也会出现该问题

select t.name,t.name,t.name
     from Teacher t LEFT OUTER JOIN Student s on t.studentid = s.id

SQL语句本身是没有问题的,不会在数据库客户端或诸如PL/SQL之类的工具中报错并且能正常查询出结果

但是Hibernate的查询却会报上面的错误,那么问题应该出在Hibernate方言或者是JDBC驱动上

解决方法是给重复的数据加上别名:

select t.name as name1,t.name as name2,t.name as name3 	
     from Teacher t LEFT OUTER JOIN Student s on t.studentid = s.id

 

参考文章:

http://stackoverflow.com/questions/4811816/sql-column-ambiguously-defined-when-run-from-hibernate

 

你可能感兴趣的:(sql,Hibernate,orm)