table of Contents
Review how MyBatis operates the database
Mapper.xml attribute value analysis
Add, delete, and modify operations
Review how MyBatis operates the database
Let us first review a line of MyBatis operating database.
1. First write the method name on the dao layer
public interface UserDao {
List<User> getUserList();
}
2. Specify the method id and return value type in the specific xml file, and write the sql statement
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.lt.dao.UserDao">
<!--select查询语句-->
<select id="getUserList" resultType="com.lt.pojo.User">
select * from mybatis.user
</select>
</mapper>
3. Execute the query in the test class.
//第一步:获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
namespace
The name of the namespace must be the same as the path name of the Dao interface
Mapper.xml attribute value analysis
-
id: corresponding to the method name in the dao interface;
-
resultType: The return value of the Sql statement execution!
-
parameterType: parameter type!
Add, delete, and modify operations
<insert id="addUser" parameterType="com.kuang.pojo.User">
insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd});
</insert>
<update id="updateUser" parameterType="com.kuang.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id = #{id} ;
</update>
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id};
</delete>
Note that all addition, deletion and modification operations require the submission of transactions
You can also set to automatically commit transactions when creating files in the MybatisUtils tool class
Almighty Map
We have written a few lines earlier, and we found that there are two problems
First, in sql, id must be equal to {id}, name must be equal to {name},
The second is that if you use a custom entity class such as User as a parameter object, we need to write out each field of the entity class, but if we use Map, you can pass any parameter you want to pass
Example: Use map to modify user name
Open the database to view the modified results
You can use map to customize the number of parameters passed, and the field names passed are mainly based on the actual call, which can be inconsistent with the database table field names.
Fuzzy query
When using fuzzy queries, do not use the percent sign in the SQL statement, because the format of the dead SQL is very unsafe and will be attacked by SQL injection.