[Solved] spring+mybatis+mysql can select but can not insert, no error, that is, no data is written

Keywords: Database Mybatis MySQL SQL


Premise: web development, spring+mybatis+mysql, using mybatis to automatically generate plug-ins to automatically generate various classes, mapping documents and so on from database forms.

Symptoms: When the user registration function is implemented, it is found that insert user data is not available. When the controller calls the insert method, it shows normal, no error, and the model can normally transmit user information, but when it checks the database, it finds that there is no data.

Reason:

It should be that Dao's corresponding method did not call the corresponding sql statement of mapper.xml.

Generally speaking, classes, mapping files generated automatically by mybatis Generator default to empty, as follows:

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

       ......

 }


As can be seen from the above code, the execution of these methods we call is empty, so we know that the data is not insert into the database.

Solution:

Define the method we call and call the sql statement defined by mapper.xml in the method to write to the database.

The code is as follows:


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

    ......

 }

In this way, after the insertion is completed in the controller, the data can be found in mysql, the data can be written successfully, and the insert is successful.

Posted by marijn on Tue, 12 Feb 2019 17:30:17 -0800