【已解决】spring+mybatis+mysql能够select但无法insert,不报错,就是无数据写入

本文解决了使用MyBatis在Spring框架下无法插入数据的问题。通过调整UserServiceImpl类中的insert方法,使其正确调用UserMapper接口,实现了用户注册功能。

前提:web开发,spring+mybatis+mysql,使用mybatis自动生成插件自动由数据库表单生成各种类、映射文档等等。

症状:在用户注册功能实现时候,发现无法insert用户数据,controller调用insert方法后显示正常,没有报错,model也能正常传递用户信息,但一查数据库,发现并没有数据。

原因:

  应该是Dao的相应method没有调用到相应mapper.xml的sql语句。

  一般来说,由mybatisGenerator自动生成的类、映射文件等,Dao接口方法默认为空,如下所示:

package com.rgl.service.Impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.rgl.IDao.UserMapper;
import com.rgl.domain.User;
import com.rgl.domain.UserExample;
import com.rgl.service.IUserService;

@Service
public class UserServiceImpl implements IUserService{

	@Autowired
	public UserMapper userMapper;

	public int insert(User record) {
		// TODO Auto-generated method stub
		return 0;
	}

	public int insertSelective(User record) {
		// TODO Auto-generated method stub
		return 0;
	}

	public List<User> selectByExample(UserExample example) {
		// TODO Auto-generated method stub
		return null;
	}

       ......

 }


  从上面的代码可以看到,这些我们调用的方法的执行都是空的,因此可知,数据并没有insert到数据库中。

解决办法:

  定义我们调用的method,在method中调用mapper.xml定义的sql语句进行写入到数据库中。

  改后的代码如下:


package com.rgl.service.Impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.rgl.IDao.UserMapper;
import com.rgl.domain.User;
import com.rgl.domain.UserExample;
import com.rgl.service.IUserService;

@Service
public class UserServiceImpl implements IUserService{

	@Autowired
	public UserMapper userMapper;
	
	public int insert(User record) {
		// TODO Auto-generated method stub
		this.userMapper.insert(record);
		return 0;
	}

	public int insertSelective(User record) {
		// TODO Auto-generated method stub
		this.userMapper.insertSelective(record);
		return 0;
	}

	public List<User> selectByExample(UserExample example) {
		// TODO Auto-generated method stub
		return null;
	}

    ......

 }

  这样,在controller中完成插入后,再进入mysql就能查到数据了,数据成功写入,insert成功。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值