Error getting nested result map values for 'company'. Cause: java.sql.SQLException: Invalid value for getInt() - 'NFHK188'
我今天遇到一个我不解的问题,是mybatis多对一关系查询出问题了,但是我自己还是解决了,在网上也查过那个错误,可是找不到我想要的。不知道你们遇到过没有,我接下来分享给大家。希望我这个第一篇博客能帮助到大家!
我定义的两个表information(航班信息表),company(航空公司表)。
CREATE TABLE `aviation`.`information` (
`id` VARCHAR(45) NOT NULL COMMENT '航班编号',
`cid` INT NOT NULL COMMENT '航空公司编号',
`start` VARCHAR(45) NULL COMMENT '出发地',
`end` VARCHAR(45) NULL COMMENT '目的地',
`start_time` TIMESTAMP NULL COMMENT '出发时间',
`seat_count` INT NULL COMMENT '座位总数',
`price` FLOAT NULL COMMENT '票价',
PRIMARY KEY (`id`))COMMENT = '航班信息表';
CREATE TABLE `aviation`.`company` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT '公司编号',
`name` VARCHAR(45) NOT NULL COMMENT '公司名称',
`prefix` VARCHAR(45) NOT NULL COMMENT '公司名称前缀',
PRIMARY KEY (`id`))COMMENT = '航空公司表';
ALTER TABLE `aviation`.`information`
ADD INDEX `FK_cid_idx` (`cid` ASC);
ALTER TABLE `aviation`.`information`
ADD CONSTRAINT `FK_cid`
FOREIGN KEY (`cid`)
REFERENCES `aviation`.`company` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
select * from information;
select * from company;
insert into company(name,prefix) values('中国国航','ZGGH');
insert into company(name,prefix) values('东方航空','DFHK');
insert into company(name,prefix) values('南方航空','NFHK');
insert into company(name,prefix) values('海南航空','HNHK');
insert into company(name,prefix) values('奥凯航空','Okey');
insert into company(name,prefix) values('首都航空','SHOU');
insert into information values('ZGGH120',1,'长沙','昆明',now(),280,320);
insert into information values('ZGGH147',1,'长沙','北京',now(),280,799);
insert into information values('Okey177',5,'长沙','三亚',now(),280,589);
insert into information values('SHOU182',6,'北京','长沙',now(),280,466);
insert into information values('DFHK232',2,'上海','昆明',now(),280,556);
insert into information values('NFHK128',3,'长沙','上海',now(),280,560);
insert into information values('NFHK188',1,'长沙','北京',now(),280,799);
insert into information values('HNHK298',4,'海南','长沙',now(),280,800);
insert into information values('SHOU180',6,'北京','昆明',now(),280,490);
insert into information values('DFHK233',2,'上海','杭州',now(),280,500);
上面这个是MySQL数据库里面的一些建表,添加约束,和插入数据的sql语句。
<-------------------------------------------------------------------------------------------------------------------------------------------------------------------------->
Information Bean(航班信息实体)
/**
*
*/
package org.hopetech.mybatis.entity;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* @author Administrator 航班信息实体类(实现序列化接口)
*
*/
@SuppressWarnings("serial")
public class Information implements Serializable {
private String id;// 编号
private Integer cid;// 航空公司编号(外键)
private String start;// 出发地
private String end;// 目的地
private Timestamp startTime;// 出发时间
private Integer seatCount;// 座位个数
private Float price;// 票价
private Company company;// 所属航空公司
// 此处省略get,set方法
}
<-------------------------------------------------------------------------------------------------------------------------------------------------------------------------->
Company Bean 航空公司实体
/**
*
*/
package org.hopetech.mybatis.entity;
import java.io.Serializable;
/**
* @author Administrator 航空公司实体类(实现序列化接口)
*
*/
@SuppressWarnings("serial")
public class Company implements Serializable {
private Integer id;// 编号
private String name;// 名称
private String prefix;// 前缀
// 此处省略get,set方法
}
<-------------------------------------------------------------------------------------------------------------------------------------------------------------------------->
Information.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.hopetech.mybatis.dao.InformationDao">
<!-- 航班信息结果映射 -->
<resultMap type="org.hopetech.mybatis.entity.Information" id="resultInformationMap">
<id column="id" property="id"/>
<result column="cid" property="cid"/>
<result column="start" property="start"/>
<result column="end" property="end"/>
<result column="start_time" property="startTime"/>
<result column="seat_count" property="seatCount"/>
<result column="price" property="price"/>
</resultMap>
<!-- 航班信息和航空公司结果映射(多对一关联) -->
<resultMap type="org.hopetech.mybatis.entity.Information" id="resultInformationCompanyMap" extends="resultInformationMap">
<association property="company" javaType="org.hopetech.mybatis.entity.Company">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="prefix" property="prefix"/>
</association>
</resultMap>
<!-- 查询航班信息和航空公司信息(动态查询) -->
<select id="dynamicQueryInformationCompany" resultMap="resultInformationCompanyMap" parameterType="org.hopetech.mybatis.entity.Information">
select i.*,c.* from information i inner join company c on c.id = i.cid
<where>
<if test="cid!=null">and i.cid=#{cid}</if>
<if test="start!=null">and i.start=#{start}</if>
<if test="end!=null">and i.end=#{end}</if>
<if test="startTime!=null">and i.start_time=#{startTime}</if>
</where>
</select>
</mapper>
<-------------------------------------------------------------------------------------------------------------------------------------------------------------------------->
Company.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.hopetech.mybatis.dao.ICompanyDao">
</mapper>
上面这个Company.xml映射文件只需要定义好基本格式加上接口,不需要写任何代码。
<-------------------------------------------------------------------------------------------------------------------------------------------------------------------------->
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0/EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
<typeAliases>
</typeAliases>
<environments default="MySQL5.5.28">
<environment id="MySQL5.5.28">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=UTF-8" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<!-- mybatis的mapper文件,每个xml配置文件对应一个接口 -->
<mappers>
<mapper resource="org/hopetech/mybatis/entity/Information.xml" />
<mapper resource="org/hopetech/mybatis/entity/Company.xml" />
</mappers>
</configuration>
<-------------------------------------------------------------------------------------------------------------------------------------------------------------------------->
Java代码:接口和实现类
/**
*
*/
package org.hopetech.mybatis.dao;
/**
* @author Administrator 航空公司数据访问层接口
*
*/
public interface ICompanyDao {
}
<-------------------------------------------------------------------------------------------------------------------------------------------------------------------------->
/**
*
*/
package org.hopetech.mybatis.dao;
import java.util.List;
import org.hopetech.mybatis.entity.Information;
/**
* @author Administrator 航班信息数据访问层接口
*
*/
public interface InformationDao {
/**
* 动态查询航班信息和航空公司信息
* @param Information 航班信息实体
* @return 航班信息和航空公司信息
*/
public List<Information> dynamicQuery(Information information);
}
<-------------------------------------------------------------------------------------------------------------------------------------------------------------------------->
/**
*
*/
package org.hopetech.mybatis.dao.impl;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.hopetech.mybatis.dao.InformationDao;
import org.hopetech.mybatis.entity.Information;
import org.hopetech.mybatis.util.MyBatisUtil;
/**
* @author Administrator 航班信息数据访问层接口实现类
*
*/
public class InformationDaoImpl implements InformationDao {
/**
* 动态查询航班信息和航空公司信息
* @param Information 航班信息实体
* @return 航班信息和航空公司信息
*/
@Override
public List<Information> dynamicQuery(Information information) {
SqlSession session = MyBatisUtil.getSqlSession();
List<Information> list = session.selectList("org.hopetech.mybatis.dao.InformationDao.dynamicQueryInformationCompany", information);
MyBatisUtil.closeSqlSession();
return list;
}
}
<-------------------------------------------------------------------------------------------------------------------------------------------------------------------------->
/**
*
*/
package org.hopetech.mybatis.util;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
* @author Administrator MyBatis工具类
*/
public class MyBatisUtil {
private static final String RESOURCE = "mybatis-config.xml";
private static SqlSessionFactory sqlSessionFactory;
private static ThreadLocal<SqlSession> localSession = new ThreadLocal<SqlSession>();
static {
Reader reader = null;
try {
reader = Resources.getResourceAsReader(RESOURCE);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
sqlSessionFactory = builder.build(reader);
} catch (Exception e) {
System.err.println("建立SqlSessionFactory错误" + e);
throw new ExceptionInInitializerError(e);
}
}
public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
public static SqlSession getSqlSession() {
SqlSession sqlSession = localSession.get();
if (sqlSession == null) {
sqlSession = (sqlSessionFactory != null) ? sqlSessionFactory.openSession() : null;
localSession.set(sqlSession);
}
return sqlSession;
}
public static void closeSqlSession() {
SqlSession sqlSession = localSession.get();
localSession.set(null);
if (sqlSession != null) {
sqlSession.close();
}
}
}
<-------------------------------------------------------------------------------------------------------------------------------------------------------------------------->
/**
*
*/
package org.hopetech.mybatis.test;
import java.util.List;
import org.hopetech.mybatis.dao.InformationDao;
import org.hopetech.mybatis.dao.impl.InformationDaoImpl;
import org.hopetech.mybatis.entity.Information;
/**
* @author Administrator 航班信息测试类
*
*/
public class InformationTest {
/**
* @param args
*/
public static void main(String[] args) {
InformationDao idi = new InformationDaoImpl();
Information information = new Information();
information.setCid(1);
List<Information> list = idi.dynamicQuery(information);
System.out.println(list.size());
for (Information info : list) {
System.out.println(info.getId());
}
}
}
<-------------------------------------------------------------------------------------------------------------------------------------------------------------------------->
运行以上代码需要加Mybatis.jar包,还有log4j.jar包,以及mysql.jar包等。
打了这么久的代码终于可以运行结果了:
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Opening JDBC Connection
DEBUG - Created connection 979294118.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@3a5ed7a6]
DEBUG - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@3a5ed7a6]
DEBUG - ==> Preparing: select i.*,c.* from information i inner join company c on c.id = i.cid WHERE i.cid=?
DEBUG - ==> Parameters: 1(Integer)
Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.apache.ibatis.executor.ExecutorException: Error getting nested result map values for 'company'. Cause: java.sql.SQLException: Invalid value for getInt() - 'NFHK188'
### The error may exist in org/hopetech/mybatis/entity/Information.xml
### The error may involve org.hopetech.mybatis.dao.InformationDao.dynamicQueryInformationCompany-Inline
### The error occurred while setting parameters
### SQL: select i.*,c.* from information i inner join company c on c.id = i.cid WHERE i.cid=?
### Cause: org.apache.ibatis.executor.ExecutorException: Error getting nested result map values for 'company'. Cause: java.sql.SQLException: Invalid value for getInt() - 'NFHK188'
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:23)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:107)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:98)
at org.hopetech.mybatis.dao.impl.InformationDaoImpl.dynamicQuery(InformationDaoImpl.java:27)
at org.hopetech.mybatis.test.InformationTest.main(InformationTest.java:25)
Caused by: org.apache.ibatis.executor.ExecutorException: Error getting nested result map values for 'company'. Cause: java.sql.SQLException: Invalid value for getInt() - 'NFHK188'
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.applyNestedResultMappings(DefaultResultSetHandler.java:808)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.getRowValue(DefaultResultSetHandler.java:763)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleRowValuesForNestedResultMap(DefaultResultSetHandler.java:730)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleRowValues(DefaultResultSetHandler.java:262)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleResultSet(DefaultResultSetHandler.java:234)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleResultSets(DefaultResultSetHandler.java:152)
at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:57)
at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:70)
at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:57)
at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:259)
at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:132)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:105)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:81)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:104)
... 3 more
Caused by: java.sql.SQLException: Invalid value for getInt() - 'NFHK188'
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2728)
at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2816)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.ibatis.logging.jdbc.ResultSetLogger.invoke(ResultSetLogger.java:60)
at com.sun.proxy.$Proxy2.getInt(Unknown Source)
at org.apache.ibatis.type.IntegerTypeHandler.getNullableResult(IntegerTypeHandler.java:34)
at org.apache.ibatis.type.IntegerTypeHandler.getNullableResult(IntegerTypeHandler.java:23)
at org.apache.ibatis.type.BaseTypeHandler.getResult(BaseTypeHandler.java:51)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.createRowKeyForMappedProperties(DefaultResultSetHandler.java:898)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.createRowKey(DefaultResultSetHandler.java:860)
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.applyNestedResultMappings(DefaultResultSetHandler.java:785)
... 16 more
解决如上错误:只需要把数据库的company表id改为cid即可。不要问为什么,我也不知道,有哪位大神可以解说,尽管评论。谢谢大家的支持!
Error getting nested result map values for 'company'. Cause: java.sql.SQLException: Invalid value for getInt() - 'NFHK188'的更多相关文章
- java.sql.SQLException: Invalid parameter object type. Expected 'java.util.Map' but found 'java.lang.String 转载
java.sql.SQLException: Invalid parameter object type. Expected 'java.util.Map' but found 'java.lang. ...
- java.sql.SQLException: Streaming result set com.mysql.jdbc.RowDataDynamic@27ce24aa is still active. No statements may be issued when any streaming result sets are open and in use on a given connection
在Sqoop往mysql导出数据的时候报了这个错误,一开始还以为是jar包没有打进去或者打错位置了,未解便上网查询. Error reading from database: java.sql.SQL ...
- org.springframework.jdbc.UncategorizedSQLException: Error attempting to get column 'alarmGroup' from result set. Cause: java.sql.SQLException: Error
异常展示: org.springframework.jdbc.UncategorizedSQLException: Error attempting to get column 'alarmGroup ...
- Cause: org.apache.ibatis.executor.ExecutorException: Error getting generated key or setting result to parameter object. Cause: java.sql.SQLException: 不支持的特性
mybatis插入数据时报错: Cause: org.apache.ibatis.executor.ExecutorException: Error getting generated key or ...
- nested exception is java.sql.SQLException: Incorrect string value: '\xE7\x99\xBB\xE9\x99\x86...' for column 'image' at row 1
HTTP Status 500 - Hibernate operation: could not insert: [cn.itcast.shop.product.vo.Product]; uncate ...
- 启动Spring boot报错:nested exception is java.sql.SQLException: Field 'id' doesn't have a default value
先看具体日志: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with n ...
- Error querying database. Cause: java.sql.SQLException: ORA-01745: 无效的主机/绑定变量名
今天调试程序是遇到了,下面的一个问题.我将对应的SQL语句拿到Toad下也能正常的执行,感觉有点莫名其妙,根据异常信息的提示查看对应的映射结果集也没发现错误,然后百度了一下,也有许多朋友也遇到过这样的 ...
- java.sql.SQLException: Before start of result set
在使用JDBC查询数据库报了这么一个错误 CREATE TABLE `d_user` ( `id` int(10) NOT NULL, `name` varchar(10) DEFAULT NULL, ...
- 解决java.sql.SQLException: ORA-01789: query block has incorrect number of result columns
java.sql.SQLException: ORA-01789: query block has incorrect number of result columns at oracle.jdbc. ...
随机推荐
- List分组 用于客服对话分组场景
工作用可能会用到会话分组: Message是消息实体对象,里面有toId和fromId 指明接收方ID和发送方Id,通过组合形式"12-22-" 为map的key public M ...
- css锚点ios不兼容的方法
css锚点的正常方法: <a href="#1f"></a> <a name="1f"></a> ios出现的问 ...
- delphi 7 mdi子窗体。。。无法更改以命令对象为源的记录集对象的 ActiveConnection 属性。
问题是这样的 我做了一个小程序 把 adoconnection放到了主窗体 连接的是access数据库; 新建了一个子窗体继承自FBase 新建了一个pubulic方法 qrySearch 实现了 ...
- Anaconda配置多spyder多python环境
作者:桂. 时间:2017-04-17 22:02:37 链接:http://www.cnblogs.com/xingshansi/p/6725298.html 前言 最近在看<统计学习方法 ...
- cookie和session的区别异同
1.用于保存页面信息:如自动登录,记住用户名 2.对于同一个网站只有一套cookie,它是以域名为单位的,一个域名就是一套,数量大小有限4k-10k,同时会具有过期时间 3.JS中通过document ...
- kafka入门
1.Kafka独特设计在什么地方?2.Kafka如何搭建及创建topic.发送消息.消费消息?3.如何书写Kafka程序?4.数据传输的事务定义有哪三种?5.Kafka判断一个节点是否活着有哪两个条件 ...
- SIP DB33标准笔记 注册/目录发送/心跳
SIP协议扩展中: 在 RFC 3261 基础上定义了一个新方法 DO.方法 DO 的功能包括:控制对方动作.更新对方信息.查询对方状态.历史监控资料查询和回放等.发送方法 DO 的请求报文时,不会创 ...
- C#事物
执行ADO.NET事务包含四个步骤,分别为: ①调用SqlConnection对象的BeginTransaction()方法,(只调用这个方法前,要打开数据库连接,否则将会出现异常) 创建一个SqlT ...
- 浅谈 angular新旧版本问题
一直在学习angularJs,之前用的版本比较老,前些天更新了一下angularJs的版本,然后发现了一些问题,希望和大家分享一下. 在老的版本里控制器直接用函数定义就可以 比如: 在angularJ ...
- java面试题—精选30道Java笔试题解答(二)
摘要: java面试题-精选30道Java笔试题解答(二) 19. 下面程序能正常运行吗() public class NULL { public static void haha(){ System ...