mybatis curd
https://blog.csdn.net/weixin_44364444/article/details/111354615?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522166432470116782427478965%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=166432470116782427478965&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_positive~default-2-111354615-null-null.142^v50^control,201^v3^control_1&utm_term=mybatis&spm=1018.2226.3001.4187
https://caochenlei.blog.csdn.net/article/details/119992847?spm=1001.2014.3001.5502
3、CRUD
3.1、namespace namespace中的包名要和Dao/mapper接口的包名保持一致
3.2、select
id:就是對應的namespace中的方法名;
resultType:Sql語句執行的返回值!
parameterType:參數類型!
package com.rui.dao; import com.rui.pojo.User; import java.util.List; public interface UserMapper { //根據id查詢用戶 User getUserById(int id); }編寫對應的mapper中的sql語句
<select id="getUserById" resultType="com.rui.pojo.User" parameterType="int"> /*定義sql*/ select * from mybatis.user where id = #{id}; </select>測試
@Test public void getUserById(){ SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); sqlSession.close(); }
3.3、Insert
3.4、Update
3.5、Delete
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!--configuration核心配置文件--> <configuration> <!--environments配置環境組--> <!--default默認環境--> <environments default="development"> <!--environment單個環境--> <environment id="development"> <!--transactionManager配置事務管理器--> <transactionManager type="JDBC"/> <!--配置連接池--> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useSSL=true&useUnicode=true"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!--每一個Mapper.xml需要在Mybatis核心配置文件中注冊--> <mappers> <mapper resource="com/newer/dao/UserMapper.xml"/> </mappers> </configuration>定義mapper層接口
package com.newer.dao; import com.newer.pojo.User; import java.util.List; public interface UserMapper { //查詢全部用戶 List<User> getUserList(); //根據ID查詢用戶 User getUserById(int id); //insert一個用戶 int addUser(User user); //修改用戶 int updateUser(User user); //刪除用戶 int deleteUser(int id); }sql語句實現mapper接口的方法
<?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"> <!--namespace綁定一個對應的Mapper接口--> <mapper namespace="com.newer.dao.UserMapper"> <select id="getUserList" resultType="com.newer.pojo.User"> select * from mybatis.user </select> <select id="getUserById" parameterType="int" resultType="com.newer.pojo.User"> select * from mybatis.user where id=#{id} </select> <insert id="addUser" parameterType="com.newer.pojo.User"> insert into mybatis.user (id,name,pwd) values (#{id},#{name },#{pwd}) </insert> <update id="updateUser" parameterType="com.newer.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> </mapper>測試
package com.newer.dao; import com.newer.pojo.User; import com.newer.utils.MyBatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; public class UserDaoTest { @Test public void test(){ //第一步:獲得SqlSession對象 SqlSession sqlSession = MyBatisUtils.getSqlSession(); //方式一:getMapper UserMapper userDao = sqlSession.getMapper(UserMapper.class); List<User> userList = userDao.getUserList(); //方式二 //List<User> userList = sqlSession.selectList("com.newer.dao.UserMapper.getUserList"); for (User user : userList) { System.out.println(user); } //關閉sqlSession sqlSession.close(); } @Test public void getUserById(){ //第一步:獲得SqlSession對象 SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); //關閉sqlSession sqlSession.close(); } //增刪改需要提交事務 @Test public void addUser(){ //第一步:獲得SqlSession對象 SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int res = mapper.addUser(new User(4, "哈哈", "12364")); if(res>0){ System.out.println("插入成功!"); } //提交事務 sqlSession.commit(); //關閉sqlSession sqlSession.close(); } @Test public void updateUser(){ //第一步:獲得SqlSession對象 SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int res = mapper.updateUser(new User(4,"呵呵","88888")); if(res>0){ System.out.println("修改成功!"); } //提交事務 sqlSession.commit(); //關閉sqlSession sqlSession.close(); } @Test public void deleteUser(){ //第一步:獲得SqlSession對象 SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int res = mapper.deleteUser(4); if(res>0){ System.out.println("刪除成功!"); } //提交事務 sqlSession.commit(); //關閉sqlSession sqlSession.close(); } }
3.6、分析錯誤
- 標簽不要匹配錯誤
- resource綁定mapper,需要使用路徑!
- 程序配置文件必須符合規范
- NullPointerException,沒有注冊到資源
- 輸出的xml文件中存在中文亂碼問題
- maven資源沒有導出問題
3.7、萬能Map
我們的實體類,或者數據庫中的表,字段或者參數過多,我們應當考慮mapper層里使用Map!
int addUser2(Map<String,Object> map);
<!--對象中的屬性,可以直接取出來 parameterType=傳遞map中的key-->
<insert id="addUser2" parameterType="map">
insert into mybatis.user (id, name, pwd) values (#{userId},#{userName},#{password});
</insert>@Test
public void addUser2(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<>();
map.put(“userId”,4);
map.put(“userName”,“王五”);
map.put(“password”,“23333”);
mapper.addUser2(map);
//提交事務
sqlSession.commit();
sqlSession.close();
}
- Map傳遞參數,直接在sql中取出key即可!【parameterType=“map”】
- 對象傳遞參數,直接在sql中取對象的屬性即可!【parameterType=“Object”】
- 只有一個基本類型參數的情況下,可以直接在sql中取到!
- 多個參數用Map,或者注解!
5.2、resultMap
結果集映射
- id name pwd
- id name password
<resultMap id="UserMap" type="User"> <!--column數據庫中的字段,property實體類中的屬性--> <result column=" id" property="id"/> <result column="name" property="name"/> <result column="pwd" property="password"/> </resultMap> <select id="getUserById" resultMap="UserMap" parameterType="int"> /*定義sql*/ select * from mybatis.user where id = #{id};
resultMap 元素是 MyBatis 中最重要最強大的元素
ResultMap 的設計思想是,對于簡單的語句根本不需要配置顯式的結果映射,而對于復雜一點的語句只需要描述它們的關系就行了。
ResultMap 最優秀的地方在于,雖然你已經對它相當了解了,但是根本就不需要顯式地用到他們。
————————————————7、分頁
為什么要分頁?------------減少數據的處理量7.1、使用Limit分頁
select * from user limit startIndex,pageSize
使用Mybatis實現分頁,核心SQL//分頁
List<User> getUserByLimit(Map<String,Integer> map);
Mapper.xml<!--分頁-->
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
測試@Test
public void getUserByLimit(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<>();
map.put("startIndex",0);
map.put("pageSize",2);
List<User> userList = mapper.getUserByLimit(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
7.2、RowBounds分頁
不再使用SQL實現分頁List<User> getUserByRowBounds();
mapper.xml<!--分頁2-->
<select id="getUserByRowBounds" resultMap="UserMap">
select * from mybatis.user
</select>
測試@Test
public void getUserByRowBounds(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//RowBounds實現
RowBounds rowBounds = new RowBounds(1, 2);
//通過java代碼層面實現分頁
List<User> userList = sqlSession.selectList("com.rui.dao.UserMapper.getUserByRowBounds",null,rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
7.3、分頁插件
8、使用注解開發
————————————————8.2、使用注解開發
注解在接口上實現
@Select(value = "select * from user") List<User> getUsers();
需要在核心配置文件中綁定接口!
<!--綁定接口--> <mappers> <mapper class="rui.dao.UserMapper"/> </mappers>測試
public class UserMapperTest { @Test public void test(){ SqlSession sqlSession = MyBatisUtils.getSqlSession(); //底層主要應用反射 UserMapper mapper = sqlSession.getMapper(UserMapper.class); List users = mapper.getUsers(); for (User user : users) { System.out.println(user); } sqlSession.close(); } }編寫接口,增加注解
public interface UserMapper { @Select(value = “select * from user”) List getUsers(); //方法存在多個參數,所有的參數前面必須加上@Param注解 @Select("select * from user where id = #{id} or name = #{name}") User getUserByID(@Param("id")int id,@Param("name")String name); @Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password})") int addUser(User user); @Update("update user set name = #{name},pwd = #{password} where id = #{id}") int updateUser(User user); @Delete("delete from user where id = #{uid}") int deleteUser(@Param("uid") int id); }
測試類
【注意:我們必須要將接口注冊綁定到我們的核心配置文件中!】
關于@Param()注解
- 基本類型的參數或者String類型,需要加上
- 引用類型不需要加
- 如果只有一個基本類型的話,可以忽略,但是建議大家都加上
- 我們在SQL中引用的就是我們這里的@Param()中設定的屬性名
#{} ${}區別
10、多對一處理
多對一:
- 多個學生,對應一個老師
- 對于學生這邊而言,關聯...多個學生,關聯一個老師【多對一】
- 對于老師而言,集合,一個老師又很多學生【一對多】
測試環境:
- 導入lombok 新建實體類Teacher,Student
- 新建Mapper接口
- 建立Mapper.XML文件
- 在核心配置文件中綁定注冊我們的MApper接口或者文件!【方式很多,隨意選】
- 測試查詢是否成功!
按照查詢嵌套處理
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.newer.dao.StudentMapper"> <!--1.查詢所有學生信息 2.根據查詢出來的學生的tid,尋找對應的老師 --> <select id="getStudent" resultMap="StudentTeacher"> select * from student </select> <resultMap id="StudentTeacher" type="Student"> <result property="id" column="id"></result> <result property="name" column="name"></result> <!--復雜的屬性,需要單獨處理 對象:association 集合:collection --> <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association> </resultMap> <select id="getTeacher" resultType="Teacher"> select * from teacher where id=#{id} </select> </mapper>
按照結果嵌套處理<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.newer.dao.StudentMapper">
<!--按照結果嵌套處理-->
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname,t.id tid
from student s,teacher t
where s.tid=t.id
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
<association property="teacher" javaType="Teacher">
<result property="id" column="tid"></result>
<result property="name" column="tname"></result>
</association>
</resultMap>
</mapper>
回顧Mysql多對一查詢方式:
- 子查詢
- 聯表查詢
11、一對多處理
比如:一個老師擁有多個學生!
對于老師而言,就是一對多的關系!
@Data
public class Teacher {
private int id;
private String name;
//一個老師擁有多個學生
private List<Student> students;
}@Data public class Student { private int id; private String name; private int tid; }
//按照結果嵌套處理 select s.id sid,s.name sname,t.name tname,t.id tid from student s,teacher t where s.tid=t.id and t.id = #{tid} //按照查詢嵌套處理 select * from mybatis.teacher where id = #{tid} select * from mybatis.student where tid = #{tid}
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.newer.dao.TeacherMapper"> <select id="getTeacher" resultMap="TeacherStudent"> select s.id sid ,s.name sname,t.name tname,t.id tid from student s,teacher t where s.tid=t.id and t.id=#{tid} </select> <resultMap id="TeacherStudent" type="Teacher"> <result property="id" column="tid"></result> <result property="name" column="tname"></result> <collection property="students" ofType="Student"> <result property="id" column="sid"></result> <result property="name" column="sname"></result> <result property="tid" column="tid"></result> </collection> </resultMap> <!--=====================================================--> <select id="getTeacher2" resultMap="TeacherStudent2"> select * from teacher where id=#{tid} </select> <resultMap id="TeacherStudent2" type="Teacher"> <collection property="students" column="id" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId"></collection> </resultMap> <select id="getStudentByTeacherId" resultType="Student"> select * from student where tid=#{tid} </select> </mapper>
關聯-association【多對一】
集合-collection 【一對多】
javaType & ofType
JavaType用來指定實體類中屬性的類型
ofType用來指定映射到List或者集合中的pojo類型,泛型中的約束類型!
注意點:保證SQL的可讀性,盡量保證通俗易懂
注意一對多和多對一中,屬性名和字段的問題!
如果問題不好排查錯誤,可以使用日志,建議使用Log4j
慢SQL 1S 1000S面試高頻:
Mysql引擎
InnoDB底層原理
索引
索引優化!
12、動態SQL
動態SQL:動態SQL就是指根據不同的條件生成不同的SQL語句動態 SQL 元素和 JSTL 或基于類似 XML 的文本處理器相似。在 MyBatis 之前的版本中,有很多元素需要花時間了解。MyBatis 3 大大精簡了元素種類,現在只需學習原來一半的元素便可。MyBatis 采用功能強大的基于 OGNL 的表達式來淘汰其它大部分元素。
if
choose (when, otherwise)
trim (where, set)
foreach
————————————————
版權聲明:本文為CSDN博主「最小的帆也能遠航」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_44364444/article/details/111354615

浙公網安備 33010602011771號