Mybatis insert插入数据注意事项

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();
		}
    }

参考文章

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值