SpringBoot+maven整合mybatis实现增删改查

第一种方式:SpringBoot整合Mybatis注解开发
首先创建一个maven项目 SpringBoot+maven整合mybatis实现增删改查_第1张图片在pom.xml文件中添加maven的相关依赖



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.3.RELEASE
         
    
    com.my.withub
    springbootmybatis
    1.0-SNAPSHOT
    
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.1.1
        
        
            mysql
            mysql-connector-java
            5.1.26
        
        
            org.springframework.boot
            spring-boot-devtools
            true
        
    

在application.yml文件中添加数据源等相关配置

mybatis:
  type-aliases-package: com.my.withub.domain
spring:
  datasource:
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8
    username: root
    password: 123456

springboot会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中

在启动类中添加对mapper包扫描注解@MapperScan

@SpringBootApplication
@MapperScan("com.my.withub.mapper")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

编写写实体类UserEntity

public class UserEntity implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    private String userName;
    private String passWord;
    private UserSexEnum userSex;
    private String nickName;

省略构造方法、getter setter以及toString方法
建表语句如下:

  CREATE TABLE `users` (
            `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
             `userName` varchar(32) DEFAULT NULL COMMENT '用户名',
             `passWord` varchar(32) DEFAULT NULL COMMENT '密码',
             `user_sex` varchar(32) DEFAULT NULL,
             `nick_name` varchar(32) DEFAULT NULL,
             PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;

然后编写mapper文件

public interface UserMapper {
    @Select("SELECT * FROM users")
    @Results({
            @Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),
            @Result(property = "nickName", column = "nick_name")
    })
    List getAll();

    @Select("SELECT * FROM users where id=#{id}")
    @Results({
            @Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),
            @Result(property = "nickName", column = "nick_name")
    })
    UserEntity getOne(Long id);

    @Insert("INSERT INTO users(userName,passWord,user_sex,nick_name) VALUES(#{userName}, #{passWord}, #{userSex},#{nickName})")
    void insert(UserEntity user);

    @Update("update users set userName=#{userName},nick_name=#{nickName} where id=#{id}")
    void update(UserEntity user);

    @Delete("delete from users where id=#{id}")
    void delere(UserEntity user);
}

其中user_sex使用了枚举

public enum UserSexEnum {
	MAN, WOMAN
	}

@Select注解表示查询,所有的查询均使用这个
@Result 修饰返回的结果集,实体类属性与数据库字段一一对应,如果实体类属性和数据库属性名保持一致,就不需要这个属性来修饰。
@Insert 插入数据,直接传入实体类会自动解析属性到对应的值
@Update 修改数据,也可以直接传入对象
@delete 删除数据
编写Controller

@RestController
public class UserController {
    @Resource
    private UserMapper userMapper;

    @RequestMapping("/add")
    public void save(UserEntity user) {
        userMapper.insert(user);
    }

    @RequestMapping("/update")
    public void update(UserEntity user) {
        userMapper.update(user);
    }

    @RequestMapping("/delete")
    public void delete(UserEntity user) {
        userMapper.delere(user);
    }

    @RequestMapping("/getUser")
    public UserEntity  getUser(Long id) {
        UserEntity  user=userMapper.getOne(id);
        return user;
    }

    @RequestMapping("/getUsers")
    public List getUsers() {
        List users=userMapper.getAll();
        return users;
    }

接下来就可以测试了

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
    @Resource
    private UserMapper userMapper;

    @Test
    public void testInsert() throws Exception {
        UserEntity user = new UserEntity();
        userMapper.insert(new UserEntity("大辉辉", "123456", UserSexEnum.MAN,"dahuihui"));
        userMapper.insert(new UserEntity("小灰灰", "123456", UserSexEnum.WOMAN,"xiaohuihui"));
        userMapper.insert(new UserEntity("樱桃小丸子", "123456", UserSexEnum.WOMAN,"xiaowanzi"));
    }

    @Test
    public void testUpdate(){
        UserEntity users = userMapper.getOne(3L);
        System.out.println(users.toString());
        users.setUserName("小丸子头");
        users.setNickName("xiaowanzitou");
        userMapper.update(users);
    }

    @Test
    public void testDelete() {
        UserEntity users = userMapper.getOne(32L);
        System.out.println(users.toString());
        userMapper.delere(users);
    }

第二种方式:SpringBoot整合Mybatis配置文件xml开发
pom.xml配置文件和注解开发一致,只需要在application.yml文件中添加如下配置
SpringBoot+maven整合mybatis实现增删改查_第2张图片
mybatis.config-location: classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations: classpath:mybatis/mapper/*.xml

在mybatis-config.xml配置文件添加相关配置




    
        
        
        
        
        
        
    

编写user的mapper映射文件UserMapper.xml




    
        
        
        
        
        
    

    
        id, userName, passWord, user_sex, nick_name
    

    

    

    
        INSERT INTO
            users
            (userName,passWord,user_sex,nick_name)
        VALUES
            (#{userName}, #{passWord}, #{userSex},#{nickName})
    

    
        UPDATE
        users
        SET
        userName = #{userName},
        passWord = #{passWord},
        nick_name = #{nickName}
        WHERE
        id = #{id}
    

    
        DELETE FROM
            users
        WHERE
            id =#{id}
    

编写Dao层的代码

public interface UserMapper {
    List getAll();

    UserEntity getOne(Long id);

    void insert(UserEntity user);

    void update(UserEntity user);

    void delete(Long id);
}

controller与测试代码和注解一致就不贴代码了

你可能感兴趣的:(SpringBoot+maven整合mybatis实现增删改查)