MyBatis細細研磨(2)——增刪改查

MyBatis細細研磨(1)——快速構建中,對MyBatis作了初步入門的介紹,環(huán)境的搭建和一個簡單的新增功能,本次詳細的介紹CRUD的使用

在上個范例中,只使用了XML的方式,調用SQL語句,也是直接調用,并沒有寫持久層的代碼

1.將XML于java代碼結合使用

  • 創(chuàng)建持久層接口代碼
package com.funshion.dao;
import com.funshion.model.User;
public interface UserDao {
    public int insert(User user);
}

  • 直接調用接口代碼
@Test
public void testInsertByJava() {
    User user = new User();
    user.setId(3l);
    user.setAge(12);
    user.setName("王五");
    UserDao userDao = sqlSession.getMapper(UserDao.class);
    userDao.insert(user);
    sqlSession.commit();
}

如代碼中所示,我們使用sqlSessiongetMapper方法,就是獲取到UserDao,調用insert方法進行操作

注意:

映射文件名要與MyBatis配置文件中的名稱要一致

image.png

映射文件中的namespace要與類名一致

image.png

2.使用注解
對于一些簡單的SQL,使用XML就顯得非常繁瑣了,使用注解就會非常簡單方便

@Insert("insert into bd_user(id,name,age) values(#{id},#{name},#{age})")
public int insertWithAnnotation(User user);
  1. 新增時獲取數(shù)據(jù)庫自動生成的主鍵值

將數(shù)據(jù)庫中的主鍵設置為自動遞增

  • XML方式
<insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
    insert into bd_user(name,age) values(#{name},#{age})
</insert>
  • 注解方式
@Insert("insert into bd_user(id,name,age) values(#{id},#{name},#{age})")
@Options(useGeneratedKeys=true,keyProperty="id",keyColumn="id")
public int insertWithAnnotationAndGetId(User user);

4.查詢

  • 根據(jù)ID查詢一條記錄
@Select("select * from bd_user where id=#{id}")
public User get(Long id);
  • 查詢多條數(shù)據(jù)
<select id="list" resultType="com.funshion.model.User">
    select * from bd_user
</select>
public List<User> list();
  • 多條件查詢

多條件查詢時要使用Param注解

@Select("select * from bd_user where age=#{age} and name=#{name}")
public User selectByCondition(@Param("name")String name,@Param("age")int age);
  1. 更新
@Update("update bd_user set name=#{name},age=#{age} where id=#{id}")
public int update(User user);

6.刪除

@Delete("delete from bd_user where id=#{id}")
public int delete(Long id);

上述中為最基本,最簡單的CRUD操作,也是日常業(yè)務開發(fā)中必不可少的東西。在日常的開發(fā)中,查詢是用的最多,也是最繁瑣的,尤其是具有關聯(lián)關系的查詢。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容