Mybatis CRUD
- My independent blog: https://chenjiabing666.github.io/
add data<insert>
- When adding data, mybatis returns the number of affected rows by default, so there is no need to specify the
ResultType
specified return type UserMapper.java
add method to interface
/**
@param user User对象
*/
Integer reg(User user);
UserMapper.xml
add<insert>
node to file#{}
Filled in isUser
the property name of the object
<!-- 节点名称取决于需要执行的操作 -->
<!-- 例如增加操作应该使用insert节点 -->
<!-- id属性(*)的值是Java接口中的方法名称 -->
<!-- parameterType属性的值是参数类型
-->
<!-- 节点中间编写SQL语句 -->
<insert id="reg"
parameterType="cn.tedu.spring.entity.User">
INSERT INTO user (
username, password
) VALUES (
#{username}, #{password}
)
</insert>
- test
@Test
public void testReg() {
//加载Spring的配置文件
AbstractApplicationContext ac
= new ClassPathXmlApplicationContext(
"spring-mvc.xml",
"spring-dao.xml");
//获取UserMapper的bean,这个是spring通过扫描mapper.xml文件自动为mybatis自动创建的,首字母小写
UserMapper userMapper
= ac.getBean(
"userMapper", UserMapper.class);
//新建User对象
User user = new User();
user.setUsername("Tom1");
user.setPassword("123456");
//调用reg(user),进行添加,返回的是受影响的行数
Integer affectedRows
= userMapper.reg(user);
System.out.println(
"affectedRows=" + affectedRows);
ac.close();
}
Get the id of the auto-incrementing primary key when adding data in Mybatis
- First of all
mybatis
, when processing the function of adding data, it just returns受影响的行数
, so the newly added data will not be returned in the persistence layer. - If you need to get the auto-incrementing primary key
Id
, first, you need to add an attribute to theXML
mapped<insert>
node2
useGeneratedKeys
: Set whether to return the auto-incrementing primary key, iftrue
so, return it, the default isfalse
keyProperty
: Configure the fields corresponding to the auto-increment primary key in the table, because sometimes the fields of the auto-increment primary key in the table may not beid
, so you need to specify
<!-- 节点名称取决于需要执行的操作 -->
<!-- 例如增加操作应该使用insert节点 -->
<!-- id属性(*)的值是Java接口中的方法名称 -->
<!-- parameterType属性的值是参数类型
useGeneratedKeys: 指定是否返回自增主键,默认为false
keyProperty:配置自增主键在表中对应的字段
-->
<insert id="reg"
parameterType="cn.tedu.spring.entity.User" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user (
username, password
) VALUES (
#{username}, #{password}
)
</insert>
- After the
mybatis
executioninsert
method at this time, it is calledreg(user)
and returned受影响的行数
, not the value of the self-incrementing primary key at this timeid
. But when this method is called, it will beid
encapsulated into the specified方法参数
, that is, encapsulated intouser
it, so only the caller can getid
it, but the persistence layer cannot get it.
@Test
public void testReg() {
//加载Spring的配置文件
AbstractApplicationContext ac
= new ClassPathXmlApplicationContext(
"spring-mvc.xml",
"spring-dao.xml");
//获取UserMapper的bean,这个是spring通过扫描mapper.xml文件自动为mybatis自动创建的,首字母小写
UserMapper userMapper
= ac.getBean(
"userMapper", UserMapper.class);
//新建User对象,此时并没有设置id的值
User user = new User();
user.setUsername("Tom1");
user.setPassword("123456");
//调用reg(user),进行添加,返回的是受影响的行数,但是此时已经将id封装到参数User对象中了
Integer affectedRows
= userMapper.reg(user);
System.out.println(
"affectedRows=" + affectedRows);
//直接获取Uesr对象中的id值,这个是自增主键返回的值
System.out.println("id = "+user.getId());
ac.close();
}
delete data<delete>
When deleting data, the number of affected rows will be automatically returned. There is no need
delete
to define the return type in the node. The return type will only be defined when querying data.UserMapper.java
Add an interface method in
//根据id删除数据,返回受影响的行数,返回1,如果删除失败返回0
Integer deleteUserById(int id);
UserMapper.xml
configure<delete>
node in
<!-- 删除用户数据根据id
Integer deleteUserById(int id)
parameterType: 指定参数类型,这里也可以不需要指定
-->
<delete id="deleteUserById" parameterType="int">
delete from user where id=#{id}
</delete>
- Deleting data is irreversible. Usually, data is not really deleted. We will use backups, logs and other means to save data. Deletes seen in many software may be
修改
operations. Usually, there is a field in the table tois_deleted
mark whether to delete or not. If the deletion is performed, then its value will be set totrue
indicate that it has been deleted, then it will not be displayed on the client at this time, making the client think that it has been deleted.
Mybaits parameter rules
mybatis
By default, one parameter is supported, that is, there can only be one parameter in the defined interface method.- If you need to support multiple parameters, you need to use
@Param()
annotations - If the parameter type in the interface method is a basic type, the
parameterType
specified type can be omitted. If it is not a basic type, the specification requires theparameterType
specified type to be used, but it is not necessary to write
@Param()
- mybatis supports one parameter by default, that is, there can only be one parameter in the defined interface method
- When designing a java interface method, if you need to specify multiple parameters, you must use
@Param()
- If you want to support multiple parameters, you need to use
@Param()
to specify the parameters, such asInteger ChangePassword(@Param("id")Integer id,@Param("newPassword")String newPassword);
- Among them
@Param("key")
, expressions are used to extractvalue
when configuring additions, deletions, and changes .#{key}
mybaits
In the process of processing, the parameters are essentiallyMap
encapsulated. That is@Param("")
, the parameter value given in the annotation is medium, the parameter valueMap
givenkey
when calling the method is the value in the Mapvalue
, and the finalXML
use of the obtained value in the file is#{}
actually obtained by using theget(key)
method in the Map
change the data<update>
When modifying data, mybatis automatically returns the number of affected rows, so we do not need to define the return type, the default return data is the number of affected rows
Define methods in the
UserMapper.java
interface thatid
modify data based onUse
@Param()
annotations to mark multiple parameters
/**
* 修改密码
* @param id id
* @param newPassword 新密码
* @return 受影响的行数
*/
Integer ChangePassword(@Param("id")Integer id,@Param("newPassword")String newPassword);
UserMapper.xml
add<update>
node inwhere
#{}
the fields in the expression are@Param("value")
invalue
<!-- 修改密码
Integer ChangePassword(@Param("id")Integer id,@Param("newPassword")String newPassword);
-->
<update id="ChangePassword">
update user set password=#{newPassword} where id=#{id}
</update>
- testing method
@Test
public void testChangePassword() {
//加载Spring的配置文件
AbstractApplicationContext ac
= new ClassPathXmlApplicationContext(
"spring-mvc.xml",
"spring-dao.xml");
//获取UserMapper的bean,这个是spring通过扫描mapper.xml文件自动为mybatis自动创建的,首字母小写
UserMapper userMapper
= ac.getBean(
"userMapper", UserMapper.class);
//调用删除的方法
int affectRow=userMapper.ChangePassword(3, "12345895");
System.out.println(affectRow);
ac.close();
}
Case: Change User Password
User provided data
- Old Password:
oldPassword
- new password:
newPassword
step
- By
id
looking up user information - Can not be used
select * from user where id=? and password=?
, because this is case- insensitive , we should firstid
obtain user information, and then comparepassword
- Complete the verification logic in
UserserviceImpl
, if the user does not exist, throw an exception that the user does not exist, and if it exists, verify whether the original password matches the - If the user information exists, then it is necessary to verify whether the user input is
oldPassword
the same as the user information.原密码
If it is not the same, throw it out密码不匹配的异常
. If it is the same, then the password can be changed. - change Password
accomplish
- We wrote a
UserService
logic written in
public void ChangePasssword(Integer id, String oldPassword,
String newPassword) throws UserNotFoundException, PasswordNotMatchException{
User user=this.findUserById(id); //获取用户信息
if (user==null) { //如果用户信息不存在
throw new UserNotFoundException("操作失败,用户信息不存在");
}else { //用户存在,则判断原密码
if (user.getPassword().equals(oldPassword)) {//如果密码匹配
userMapper.ChangePassword(id, newPassword); //修改密码
}else { //原密码不匹配
throw new PasswordNotMatchException("操作失败,原密码不正确");
}
}
}
- Then
Controller
if you want to call this in , itChangePasssword
will judge what went wrong by handling the exception, and give a friendly prompt
Query data<select>
Query for a single piece of data
- The
id
query result returned by the query is a single piece of data, such as:select * from user where id=1
- When writing a query for a single record , you
接口方法
only need to return one实体类对象
/**
* 根据id查询用户信息
* @param id 用户id
* @return 返回User对象
*/
User findUserById(Integer id);
UserMapper.xml
configure<select>
node in- The specified return type needs to be used
resultType
, because the parameter is a primitive type, so there is no need to use theparameterType
specified parameter type
<select id="findUserById" resultType="cn.tedu.spring.entity.User">
select * from user where id=#{id}
</select>
Find multiple records
- Some lookup statements return multiple records, so we can use the
List<>
collection to receive the returned results, but not directly实体类对象
. UserMapper.java
define interface methods in
/**
* 根据密码查找用户
* @param password 用户密码
* @return 返回的是一个用户的集合
*/
List<User> findUserByPassword(String password);
UserMapper.xml
add<select>
node inresultType
Although the return here isUser集合
, but the type here still needs to write the User type- Since the parameter is a primitive type, there is no need to use
parameterType
<!--
List<User> findUserByPassword(String password);
resultType: 虽然返回的是User集合,但是这里的类型还是需要写User类型
-->
<select id="findUserByPassword" resultType="cn.tedu.spring.entity.User">
select * from user where password=#{password}
</select>
- test
@Test
public void testFindUserByPassword() {
//加载Spring的配置文件
AbstractApplicationContext ac
= new ClassPathXmlApplicationContext(
"spring-mvc.xml",
"spring-dao.xml");
//获取UserMapper的bean,这个是spring通过扫描mapper.xml文件自动为mybatis自动创建的,首字母小写
UserMapper userMapper
= ac.getBean(
"userMapper", UserMapper.class);
//获取User集合
List<User> users=userMapper.findUserByPassword("12345895");
System.out.println(users);
ac.close();
}
Summarize
xxMapper.xml
The nodes configured inid
must bexxMapper.java
the方法名
same as in- mybatis supports one parameter by default, but we can use to
@Param("")
specify multiple parameters, but when using#{}
the value, it must be@Param("")
consistent with the parameters in - Obtaining the self-incrementing primary key is not used as the return value of the method, but when the method is called, the value of the self-incrementing primary key is set in the object of the method parameter, then the caller at this time can get
自增主键
the value. - Add, modify, delete, the method returns always the number of affected rows
- ** When defining entity class attributes, try to use them
包装类
, such asInteger age**
- As long as it is a
<select>
node, the return type must be writtenresultType
, whether it is a basic type or another type