1、namespace
namespace中的包名要和Dao/mapper接口的包名一致!
2、 select
選擇,查詢語(yǔ)句;
- id:就是對(duì)應(yīng)的namespace中的方法名;
- resultType: Sql語(yǔ)句執(zhí)行的返回類型!
- parameterType:參數(shù)類型!
1.編寫接口
1
2
|
//根據(jù)id查詢用戶 User getUserById( int id); |
? 2.編寫對(duì)應(yīng)的mapper.xml中的sql語(yǔ)句
1
2
3
|
< select id= "getUserById" parameterType= "int" resultType= "com.kuang.pojo.User" > select * from mybatis. user where id = #{id} </ select > |
? 3.測(cè)試
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@Test public void getUserLike(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper. class ); List<User> userList = mapper.getUserLike( "李" ); for (User user : userList) { System.out.println(user); } sqlSession.close(); } |
3、Insert
1
2
3
4
|
<! --對(duì)象中的屬性,可以直接取出來(lái)--> < insert id= "addUser" parameterType= "com.kuang.pojo.User" > insert into mybatis. user (id, name ,pwd) values (#{id},#{ name },#{pwd}); </ insert > |
4、update
1
2
3
|
< update id= "updateUser" parameterType= "com.kuang.pojo.User" > update mybatis. user set name = #{ name },pwd=#{pwd} where id = #{id}; </ update > |
5、Delete
1
2
3
|
< delete id= "deleteUser" parameterType= "int" > delete from mybatis. user where id = #{id}; </ delete > |
注意點(diǎn):
增刪改需要提交事務(wù)(sqlSession.commit())
6、分析增刪改查會(huì)遇到的錯(cuò)誤
- 標(biāo)簽不要匹配錯(cuò)
- resource綁定mapper,需要使用路徑
- 程序配置文件必須符合規(guī)范
- NullPointerException,沒(méi)有注冊(cè)到資源!
- 輸出的xml文件中存在中文亂碼問(wèn)題!
- maven資源沒(méi)有導(dǎo)出問(wèn)題
到此這篇關(guān)于詳解Mybatis中的CRUD的文章就介紹到這了,更多相關(guān)Mybatis的CRUD內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://www.cnblogs.com/laiyw/archive/2021/03/07/14495847.html