springboot项目操作数据库之MyBatis增删改查操作
- package com.zidiu.mapper;
-
- import com.zidiu.pojo.User;
- import org.apache.ibatis.annotations.*;
-
- import java.util.List;
-
- @Mapper
- public interface UserMapper {
- /**
- * 查询全部
- */
- @Select("selec t * from user")
- public List<User> findAll();
-
- /**
- * 根据id删除
- */
- @Delete("delete from user where id = #{id}")
- public Integer deleteById(Integer id);
-
- /**
- * 添加用户
- */
- @Insert("insert into user(username,password,name,age) values(#{username},#{password},#{name},#{age})")
- public void insert(User user);
-
- /**
- * 根据id更新用户信息
- */
- @Update("update user set username = #{username},password = #{password},name = #{name},age = #{age} where id = #{id}")
- public void update(User user);
-
- /**
- * 根据用户名和密码查询用户信息
- */
- @Select("select * from user where username = #{username} and password = #{password}")
- public User findByUsernameAndPassword(@Param("username") String username, @Param("password") String password);
- }
复制代码 测试类:
- package com.zidiu;
-
- import com.zidiu.mapper.UserMapper;
- import com.zidiu.pojo.User;
- import org.junit.jupiter.api.Test;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
-
- import java.util.List;
-
- @SpringBootTest
- public class SpringbootMybatisQuickstartApplicationTests {
- @Autowired
- private UserMapper userMapper;
- @Test
- public void testFindAll(){
- List<User> userList = userMapper.findAll();
- for (User user : userList) {
- System.out.println(user);
- }
- }
- @Test
- public void testDeleteById(){
- Integer i = userMapper.deleteById(36);
- System.out.println("影响行数" + i);
- }
-
- @Test
- public void testInsert(){
- User user = new User();
- user.setUsername("admin");
- user.setPassword("123456");
- user.setName("管理员");
- user.setAge(30);
- userMapper.insert(user);
- }
-
- @Test
- public void testUpdate(){
- User user = new User();
- user.setId(6);
- user.setUsername("admin666");
- user.setPassword("123456");
- user.setName("管理员阿祥");
- user.setAge(30);
- userMapper.update(user);
- }
-
- @Test
- public void testFindByUsernameAndPassword(){
- User user = userMapper.findByUsernameAndPassword("admin666", "123456");
- System.out.println(user);
- }
- }
复制代码 完整源代码下载:
demo04.zip
(14.08 KB, 下载次数: 0, 售价: 30 金币)
说明:基于官方骨架创建的springboot项目中,接口编译时会保留方法形参名,@Param注解可以省略 (#{形参名})。
SpringBoot3+Vue3开发综合实战项目:
JavaWeb(SpringBoot3+vue3)开发+教学管理系统项目实战
|