Fork me on Gitee

Springboot集成Mybatis

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

Mybatis架构

 

 

1. 添加maven 依赖

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>

2.添加相关配置文件(数据库链接等相关配置)

 

一、无配置文件注解版

1.在启动类中添加对mapper包扫描@MapperScan(或者直接在Mapper类上面添加注解@Mapper,建议使用上面那种)

 

 2.开发Mapper

#{} 只是替换,相当于PreparedStatement使用占位符去替换参数,可以防止sql注入。${} 是进行字符串拼接,相当于sql语句中的Statement,使用字符串去拼接sql;$可以是sql中的任一部分传入到Statement中,不能防止sql注入。(比如说我们的入参是表名的时候,使用${})

    @Select 是查询类的注解,所有的查询均使用这个
    @Result 修饰返回的结果集,关联实体类属性和数据库字段一一对应,如果实体类属性和数据库属性名保持一致,就不需要这个属性来修饰。

    @Insert 插入数据库使用,直接传入实体类会自动解析属性到对应的值
    @Update 负责修改,也可以直接传入对象@delete 负责删除

 

package com.qyc.Microservice.mapper;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.qyc.Microservice.dto.User;

public interface UserMapper {

	@Insert("insert into user(age,name,password,sex) values (#{age},#{name},#{password},#{sex})")
	public void insert(User user);
	
	@Update("update user set name=#{name},age=#{age},password=#{password},sex=#{sex} where id=#{id}")
	public int update(User user);
	
	@Delete("delete from user where id=#{id}")
	public int delete(User user);
	
	@Select("select * from user where name = #{name} and password =#{password}")
	public User select(User user);
}

  

	@Test
	public void userSave() {
		User user = new User();
		user.setName("aa11a");
		user.setAge(20);
		user.setSex(0);
		user.setPassword("alsdja");
		
		userService.saveMapper(user);
	}

  

二、配置文件版

1 . pom文件和上个版本一样,只是application.properties新增以下配置
mybatis.config-locations=classpath:mybatis/mybatis-config.xml(可选)
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

 

posted @ 2021-03-22 23:02  JoePotter  阅读(45)  评论(0编辑  收藏  举报
``