Then the last article said that the last article wrote how to run it, and only wrote a query for all the sentences.
This article writes additions, deletions, modifications, and annotations to achieve additions, deletions, modifications, and mappers
Previous link: Getting started with mybatis
Achieve addition, deletion and modification
The default is to run mybatis. To realize the addition, deletion, modification, and check, you only need UserMapper
to add an interface in the UserMapper.xml
middle, write tags and sql statements in the middle, and then add a test method to the test class for testing.
You can also practice, write the interface first,
UserMapper.xml
and write the content yourself.
1. UserMapper class:
public interface UserMapper {
// 查询所有用户
List<User> findAll();
//根据id查询用户
User getUserById(int id);
//插入用户
int addUser(User user);
//更新用户
int updateUser(User user);
//删除用户
int deleteUser(int id);
}
2、UserMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lu.mapper.UserMapper">
<!--查询所有用户,resulType后要写全,只有命名别名之后才可不写全-->
<select id="findAll" resultType="com.lu.pojo.User">
select * from user
</select>
<select id="getUserById" parameterType="int" resultType="com.lu.pojo.User">
select * from user where id = #{id}
</select>
<insert id="addUser" parameterType="com.lu.pojo.User" >
insert into user (id,username, pwd) values(#{id},#{username}, #{pwd})
</insert>
<update id="updateUser" parameterType="com.lu.pojo.User">
update user set username = #{username}, pwd=#{pwd} where id=#{id}
</update>
<insert id="deleteUser" parameterType="int">
delete from user where id = #{id}
</insert>
</mapper>
3. Write test methods
In the test class, because juint's dependency is imported, it can be annotated with @Test.
The method below the @Test annotation can click the green one on the left to run this method alone.
@Test
public void getUserByIdTest(){
//创建sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//使用SqlSession创建UserMapper接口的代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//根据id查询,输入数字
User getuser = userMapper.getUserById(2);
System.out.println(getuser);
//关闭sqlSession
sqlSession.close();
}
Use annotations to implement additions, deletions, and changes
If you use annotations, it will be more brief.
Write UserMapper.xml
the sql statement to be written in the UserMapper
interface directly through the annotation , and you can directly delete the corresponding xml.
Another place to change is to add SQL mapping statements in the core configuration file.
The code after adding annotations to the UserMapper interface
public interface UserMapper {
// 查询所有用户
@Select("select * from user")
List<User> findAll();
//根据id查询用户
@Select("select * from user where id = #{id}")
User getUserById(int id);
//插入用户
@Insert("insert into user (id, username, pwd ) values(#{id}, #{username}, #{pwd} )")
int addUser(User user);
//更新用户
@Update("update user set username=#{username}, pwd=#{pwd} where id = #{id}")
int updateUser(User user);
//删除用户
@Delete("delete from user where id = #{id}")
int deleteUser(int id);
}
Add mapping to the core configuration file
Code:
<mappers>
<mapper class="com.lu.mapper.UserMapper"/>
</mappers>
Add location as shown below
XML mapper
The real power of MyBatis lies in its sentence mapping, which is its magic. Because of its exceptional power, the XML file of the mapper is relatively simple.
The SQL mapping file has only a few top-level elements (listed in the order in which they should be defined):
cache
– The cache configuration of the namespace.
cache-ref
– Refer to the cache configuration of other namespaces.
resultMap
– Describe how to load objects from the database result set, which is the most complex and powerful element.
sql
– A reusable statement block that can be referenced by other statements.
insert
– Map the insert statement.
update
– Mapping update statement.
delete
– Mapping delete statements.
select
– Map query statements.
Select element attributes
Attributes | description |
---|---|
id |
A unique identifier in the namespace can be used to quote this statement. |
parameterType |
The fully qualified class name or alias of the parameter that will be passed into this statement |
resultType |
The fully qualified name or alias of the class expected to be returned from this statement. Note that if the return is a collection, it should be set to the type contained in the collection, not the type of the collection itself. Only one of resultType and resultMap can be used at the same time. |
resultMap |
A named reference to the external resultMap. Result mapping is the most powerful feature of MyBatis. If you understand it thoroughly, many complex mapping problems can be easily solved. Only one of resultType and resultMap can be used at the same time. |
Talk about mappers
The following is from the official document:
Define SQL mapping statements. First, we need to tell MyBatis where to find these sentences. In terms of automatically finding resources, Java does not provide a good solution, so the best way is to directly tell MyBatis where to find the mapping file. You can use resource references relative to the classpath, or fully qualified resource locators (including URLs in the form of file:///), or class names and package names. E.g:
<!-- 使用相对于类路径的资源引用 -->
<mappers>
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
<mapper resource="org/mybatis/builder/BlogMapper.xml"/>
<mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
<mapper class="org.mybatis.builder.AuthorMapper"/>
<mapper class="org.mybatis.builder.BlogMapper"/>
<mapper class="org.mybatis.builder.PostMapper"/>
</mappers>
These configurations will tell MyBatis where to find the mapping file, and the remaining details should be each SQL mapping file.
There are four types of official documents, and two commonly used ones are given here.