org.apache.ibatis.binding.BindingException: Mapper method 'com… has an unsupported return type
在server中调用dao层方法时,出现以下错误,但是sql执行修改数据成功,并没有回滚问题:
Exception in thread "AWT-EventQueue-0" org.apache.ibatis.binding.BindingException: Mapper method 'com.zzk.mybatis.EmployeeMapper.insertuser' has an unsupported return type: class com.zzk.bean.User
原因是sql执行语句的返回类型出现了问题。
service层代码:
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
}
private void mybatis() throws IOException{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try{
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
Map <String,Object>map=new HashMap<>();
map.put("username", username);
map.put("password", password);
mapper.insertuser(map);
openSession.commit();
System.out.println("pk");
}finally{
openSession.close();
}
}
dao层代码:
public User insertuser(Map<String,Object> map);
mapper.xml代码:
<!--增加用户-->
<insert id="insertuser" parameterType="Map">
insert into tb_user(username,password) values(#{username},#{password})
</insert>
解决:
mapper文件中的update、insert、delete语句是不需要设置返回类型的,他们都是默认返回一个int,所以要修改dao层接口的方法:
public Integer insertuser(Map<String,Object> map);
mybatis insert 插入数据,显示执行成功,但未真正插入到数据库中
通过mybatis插入数据库,插入数据,显示成功,但是实际上数据并没有写入数据库中,通过日志可以看到原因:插入语句回滚连接数据库,导致插入失败。
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
}
private void mybatis() throws IOException{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try{
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
Map <String,Object>map=new HashMap<>();
map.put("username", username);
map.put("password", password);
mapper.insertuser(map);
openSession.commit();//将数据提交到数据库中,否则执行成功,并未真正插入到数据库中
System.out.println("pk");
}finally{
openSession.close();
}
}