MyBatis细细研磨(2)——增删改查

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/oXinYangonly/article/details/81078748

MyBatis细细研磨(1)——快速构建中,对MyBatis作了初步入门的介绍,环境的搭建和一个简单的新增功能,本次详细的介绍CRUD的使用

在上个范例中,只使用了XML的方式,调用SQL语句,也是直接调用,并没有写持久层的代码

1.将XML于java代码结合使用

  • 创建持久层接口代码
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. 新增时获取数据库自动生成的主键值
    将数据库中的主键设置为自动递增
    • 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.查询 - 根据ID查询一条记录
@Select("select * from bd_user where id=#{id}")
public User get(Long id);
  • 查询多条数据
<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操作,也是日常业务开发中必不可少的东西。在日常的开发中,查询是用的最多,也是最繁琐的,尤其是具有关联关系的查询。

猜你喜欢

转载自blog.csdn.net/oXinYangonly/article/details/81078748