MyBatis add, delete, change, check function, multiple parameters, pass values

At first, I thought that MyBatis add, delete, modify and check can pass in multiple parameters and directly assign the value with the parameter name, and then I can't find it after a bug for a long time.
Give an example

//这个是用来更新最大成绩的函数
public interface ScoreDao {
	@Update("update scores set top_score=#{score} where id=#{id}")
	public int updateTopScore(int id,int score);
}

This function must have multiple parameters, and then crazy error
org.apache.ibatis.exceptions.PersistenceException
Cause: org.apache.ibatis.binding.BindingException: Parameter 'score' not found.
Solution:
directly use the position of the parameter

public interface ScoreDao {
	@Update("update scores set top_score=#{0} where id=#{1}")
	public int updateTopScore(int id,int score);
}

Reason: because multiple parameters are passed in, mybatis will be automatically encapsulated in the map, the key is the index
Map <Integer, Object> map = new HashMap ();
so you can also define a Map as a parameter
or encapsulate it as an object

@Update("update scores set top_score=#{topScore} where id=#{id}")
	public int updateTopScore(Score score);

I just encapsulated it as a Score object.
And note that the attribute in # {} is not to write the attribute name, but to write the getter method to remove the lowercase first letter of get.
such as

private Integer topScorehaha;
public Integer getTopScore() {
	return topScorehaha;
}

# {topScore} instead of # {topScorehaha}

But my recommended method:
you can tell mybatis not to change @param to specify a name for the parameter

@Update("update scores set top_score=#{score} where id=#{id}")
	public void updateTopScore(@Param("id")int id,@Param("score")int score) ;

Summary: The
parameters can be in the following situations:
1. A single parameter:
basic type: value # {just write}, everything can be inside, because there is only one parameter, mybatis directly corresponds.
2. Multiple parameters:
Value: # {parameter name} is invalid
Available: 0, 1
Reason: Because multiple parameters are passed in, mybatis will be automatically encapsulated in the map, the key is the index
Map <Integer, Object> map = new HashMap ();
3. You can tell mybatis not to change @param to specify the name for the parameter
4. Use your own class
5. Map

If you find that the content of my article is wrong, please give me corrections. I am just a beginner who has just learned the ssm framework. Thanks.

Published 21 original articles · liked 0 · visits 721

Guess you like

Origin blog.csdn.net/D1124615130/article/details/104524778