问题描述
- hibernate查询数据转换出错
-
create table topics(
topicId int primary key AUTO_INCREMENT,
userName varchar(20) not null,
topicName varchar(100),
context varchar(300),
sendTopicTime datetime,
KEYuserName
(userName
),
CONSTRAINTFK_ID_USER
FOREIGN KEY (userName
) REFERENCESusers
(userName
)
)ENGINE=innodb;create table Users(
userId int primary key AUTO_INCREMENT,
userName varchar(20) not null unique ,
upassWord varchar(20) not null,
email varchar(20),
)ENGINE=InnoDB;映射
Users.hbm.xml:< set name="topicses" inverse="true" >
< key>
< column name="userName" not-null="true" />
< /key>
< one-to-many class="com.wing.bean.Topics" />
< /set>
Topics.hbm.xml
< many-to-one name="users" class="com.wing.bean.Users" fetch="select">
< column name="userName" not-null="true" / >
< / many-to-one>
2张表, hibernate映射问题工具生成的,查询topics时 报Invalid value for getInt() 错误。我估计是因为String 型的userName 做外键导致的,难道外键一定要是int型吗?求大神指教Caused by: java.sql.SQLException: Invalid value for getInt() - 'white'
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2709)
at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2734)
at org.hibernate.type.IntegerType.get(IntegerType.java:51)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:184)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:173)
at org.hibernate.type.ManyToOneType.hydrate(ManyToOneType.java:126)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2114)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1404)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1332)
at org.hibernate.loader.Loader.getRow(Loader.java:1230)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:603)
at org.hibernate.loader.Loader.doQuery(Loader.java:724)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
at org.hibernate.loader.Loader.doList(Loader.java:2232)
... 9 more
解决方案
看看 hibernate映射中,该字段是什么类型
解决方案二:
外键不一定要是int的,报的错能全点吗?
解决方案三:
table topics中,
KEY userName (userName),
CONSTRAINT FK_ID_USER FOREIGN KEY (userName) REFERENCES users (userName)改成
KEY userName (userName),
CONSTRAINT FK_ID_USER FOREIGN KEY (key) REFERENCES users (userID)
解决方案四:
topics 中 的username
user表