mybatis--使用预编译sql新增修改查询用户数据

新增用户数据

在接口中定义新增的方法并用insert()写入sql语句

因为新增的属性有很多 所以使用封装到对象emp里

在方法中传入emp对象

  //新增员工操作
    //获取对象中的属性要采用驼峰命名法
    @Insert("insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time)" +
            "values (#{username},#{name},#{gender},#{image},#{job},#{entrydate},#{deptId},#{createTime},#{updateTime})")
    public void insert(Emp emp);

在test启动类中构造该对象并插入数据并输出到控制台

@Test
    public void testInsert(){
        //构造员工对象
    Emp emp =new Emp();
    emp.setUsername("LingLing");
    emp.setName("汤姆");
    emp.setImage("1.jpg");
    emp.setGender((short)1);
    emp.setJob((short)1);
    emp.setEntrydate(LocalDate.of(2000,1,1));
    emp.setCreateTime(LocalDateTime.now());
    emp.setUpdateTime(LocalDateTime.now());
//    执行新增员工信息的操作
    empMapper.insert(emp);
}

启动后结果

新增(主键返回)

在数据添加成功后,需要获取插入数据库数据的主键。如:添加套餐数据时,还需要维护套餐菜品关系表数据。

例如 添加一条数据后

运行后 控制台输出的为空

是没有设置主键返回

在mapper接口中添加注解@Option

会自动将生成的主键值,赋值给emp对象id属性

 @Options(useGeneratedKeys = true,keyProperty = "id")

验证:

1 重新插入一条数据

2 在接口中声明添加注解@Option

运行项目后输出id为26

删除用户数据

@Mapper
public interface EmpMapper {
//    根据id删除数据
    @Delete("delete from emp where id= #{id}")
    //接口方法
//    public void delete(Integer id);
    //设置有返回值的类型接口
    public int delete(Integer id);
 @Autowired
    private EmpMapper empMapper;

    @Test
    public void testDelete(){
       int delete= empMapper.delete(16);
        //    delete的返回值是此次操作影响的记录数
        System.out.println(delete);
    }

更新用户数据

在mapper接口中定义方法并添加更新方法

   @Update("update emp set username=#{username},name=#{name},gender=#{gender},image=#{image},job=#{job},entrydate=#{entrydate},dept_id=#{deptId},update_time=#{updateTime}" +
            "where id = #{id};")
    public void update(Emp emp);

2 在test类中调用接口方法并插入数据


@Test
    public void testUpdate(){
    Emp emp =new Emp();
    emp.setId(18);
    emp.setUsername("LingLing5");
    emp.setName("玲玲");
    emp.setImage("1.jpg");
    emp.setGender((short)1);
    emp.setJob((short)1);
    emp.setEntrydate(LocalDate.of(2000,1,1));
    emp.setUpdateTime(LocalDateTime.now());
    emp.setDeptId(1);

    //执行更新数据
    empMapper.update(emp);

运行结果:

查询(根据ID查询)

mapper接口中定义方法

//    根据id查询员工
    @Select("select * from emp where id=#{id}")
    public Emp getById(Integer id);
//根据Id查询员工
    @Test
    public void testById(){
        //定义变量获取返回值
      Emp emp=  empMapper.getById(20);
      //在控制台输出返回值
        System.out.println(emp);
    }

输出结果 查询id为20的用户数据

查看控制台中封装的数据

说明没有封装进来

原因:类中属性名与表中的属性名不一致所以导致没有封装进来

解决数据封装问题

//    方案1 给字段起别名,让别名与实体类一致
@Select("select id, username, password, name, gender, image, job, entrydate," +
        " dept_id deptId, create_time createTime, update_time updateTime from emp where id=#{id}")
public Emp getById(Integer id);
// 方案2 通过@Results和@Result注解手动映射封装
    @Results({
            @Result(column = "dept_Id",property = "deptId"),
            @Result(column = "create_Time",property = "createTime"),
            @Result(column = "update_Time",property = "updateTime")
    })
    @Select("select * from emp where id=#{id}")
    public Emp getById(Integer id);
//    方案3 开启mybatis的驼峰命名开关 ---a_cloumn-->aColumn 在application.properties中配置
mybatis.configuration.map-underscore-to-camel-case=true



//    根据id查询员工
    @Select("select * from emp where id=#{id}")
    public Emp getById(Integer id);

查询用户根据条件查询

模糊查询like并设置了四个参数用集合封装

因为%%是占位符#也是占位符不能再引号内使用 所以用$代替‘%${name}’

    @Select("select * from emp where name like '%${name}% 'and gender =#{gender} " +
          "and entrydate between #{begin} and #{end} order by update_time desc;")
// 条件查询员工信息
    public List<Emp> list(String name, Short gender, LocalDate begin,LocalDate end);
    @Test
    public void testList(){
      List<Emp> empList= empMapper.list("张", (short) 1,LocalDate.of(2010,1,1),LocalDate.of(2020,1,1));
        System.out.println(empList);

可以使用concat()函数拼接

select concat('hello','mysql','world');
@Select("select * from emp where name like concat('%',#{name},'%') and gender =#{gender} " +
        "and entrydate between #{begin} and #{end} order by update_time desc;")

最后程序运行如图所示

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis-Plus是一个基于MyBatis的增强工具,可以简化开发过程并提供更多的便利性。下面是使用MyBatis-Plus进行SQL查询的一般步骤: 1. 确保已正确配置MyBatis-Plus和MyBatis的依赖项。 2. 创建一个Mapper接口,继承自BaseMapper或IService接口,或者使用@Mapper注解标记该接口。 3. 在Mapper接口中定义需要的SQL查询方法。可以使用@Select注解或者在XML文件中编写对应的SQL语句。 例如,假设你有一个User实体类,对应数据库中的user表,可以按照以下步骤进行SQL查询: 1. 创建UserMapper接口: ```java import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; @Mapper public interface UserMapper extends BaseMapper<User> { // 定义需要的SQL查询方法 // 例如: // @Select("SELECT * FROM user WHERE name = #{name}") // User findByName(@Param("name") String name); } ``` 2. 在MyBatis的配置文件中,配置Mapper扫描路径: ```xml <configuration> <!-- 其他配置项 --> <mappers> <package name="com.example.mapper" /> </mappers> </configuration> ``` 3. 现在你可以在你的Service或Controller中注入UserMapper,并调用其中定义的查询方法: ```java @Service public class UserService { @Autowired private UserMapper userMapper; public User getUserByName(String name) { // 调用查询方法 // 例如: // return userMapper.findByName(name); } } ``` 这样,你就可以使用MyBatis-Plus进行SQL查询了。根据具体的查询需求,可以使用不同的注解(如@Select、@Update、@Delete等)来定义SQL语句,或者在XML文件中编写对应的SQL语句。同时,MyBatis-Plus还提供了更多的查询方法和功能,可以根据需要进行调整和使用

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值