我今天遇到一个我不解的问题,是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'的更多相关文章

  1. 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. ...

  2. 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 ...

  3. 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 ...

  4. 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 ...

  5. 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 ...

  6. 启动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 ...

  7. Error querying database. Cause: java.sql.SQLException: ORA-01745: 无效的主机/绑定变量名

    今天调试程序是遇到了,下面的一个问题.我将对应的SQL语句拿到Toad下也能正常的执行,感觉有点莫名其妙,根据异常信息的提示查看对应的映射结果集也没发现错误,然后百度了一下,也有许多朋友也遇到过这样的 ...

  8. java.sql.SQLException: Before start of result set

    在使用JDBC查询数据库报了这么一个错误 CREATE TABLE `d_user` ( `id` int(10) NOT NULL, `name` varchar(10) DEFAULT NULL, ...

  9. 解决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. ...

随机推荐

  1. DIV+CSS清除浮动方法

    一.为什么要清除浮动? 1>父元素在未定义高的情况下,由于子元素全部浮动脱离文本流,而造成父元素高的塌陷(正常情况下,父元素的高是由未浮动的子元素撑起来) 2>因为部分子元素的而浮动,脱离 ...

  2. 微信小程序,前端大梦想(三)

    微信小程序的事件及生命周期   继续下节课,今天我们还是从四个方面来了解小程序:     ●常用事件和事件冒泡   ●配置   ●app生命周期及app对象的使用   ●页面的生命周期   一.事件的 ...

  3. 倒排索引的AND操作

    这是一道来自百度的面试题.倒排索引的AND操作. 倒排索引是以关键词作为索引项来索引文档的一种机制,如图中Brutus.Calpurnia.Caesar为关键词,2.4.8等等为文档ID. 现在有一个 ...

  4. JavaWeb开发之HttpServletResponse

    1. HttpServletResponse简介 Web服务器回送给Web客户端的HTTP响应消息分为三个部分:状态行,响应消息头,响应体. Servlet API中定义了ServletRespons ...

  5. [ext4]磁盘布局 - group分析

    ext4文件系统的磁盘布局是先把磁盘分成一个个相同大小的block块(每个block块的大小默认是4K),然后把这些block块合成一个个group. group大小最大为256M(默认为256M), ...

  6. Fish Shell

    今天看到阮一峰同学的一篇博客(Fish shell 入门教程),讲述的非常详细.清楚,有兴趣的可以直接转去查看此文,本文仅提供一下个人使用心得. 一.fish shell 想必接触过类unix(包括w ...

  7. JavaScript中变量、参数、函数之间的关系

    ------------------------------ 废话不多说,直接开始. 我们看一段代码(参考其他资料所得) <script type="text/javascript&q ...

  8. poj3304计算几何直线与线段关系

    Given n segments in the two dimensional space, write a program, which determines if there exists a l ...

  9. 使用了UnityEditor中的API,打包时却不能打包UnityEditor的问题

    前段时间写了一篇名叫<Unity使用Windows弹窗保存图片>的文章 然而现在项目进入了测试阶段 就在发布的时候,这个地方出问题了 问题出在using UnityEditor; 如上文章 ...

  10. Struts2拦截器登录验证

    Struts2拦截器 Struts2拦截器的概念和Spring Mvc拦截器一样. Struts2拦截器是在访问某个Action或Action的某个方法,字段之前或之后实施拦截,并且Struts2拦截 ...