mybatis常用的注解

1. 增删改查注解

1.1 @Insert和@Options

public interface UserDAO{
	@Options(useGeneratedKeys = true,keyColumn = "uid", keyProperty = "id")
	@Insert("insert into t_user(username,password,gender,birth) values(#{username},#{password},#{gender},#{birth})")
	public void insertUser(User user);
}

  • 设置@Options属性userGeneratedKeys的值为true,并指定实例对象中主键的属性名keyProperty=“id”,以及在数据库中的字段名keyColumn=“uid”。这样在user插入数据后,userId属性会被自动赋值

1.2 @Delete

public interface UserDAO{
	@Delete("delete from t_user where id = #{id}")
	public void deleteUserById(@Param("id") int id);
}

1.3 @Update

public interface UserDAO{
	@Update("update t_user set username=#{usernmae},password=#{password}")
	public void updateUser(User user);
}

1.4 Select

public interface UserDAO{
	@Select("select * from t_user where id = #{id} and username = {#username}")
	public User queryUserbyId(@Param("id") int id,@Param("username") String username);
}

2. 编译之后生成相应的实现类

2.1 @Mapper

@Mapper注解:

  1. 作用:在接口类上添加了@Mapper,在编译之后会生成相应的接口实现类
  2. 添加位置:接口类上面
@Mapper
public interface UserDAO {
 
}

如果想要每个接口都要变成实现类,那么需要在每个接口类上加上@Mapper注解,比较麻烦,解决这个问题用@MapperScan

2.2 @MapperScan

  1. 作用:包下面的所有接口在编译之后都会生成相应的实现类
  2. 添加位置:是在Springboot启动类上面添加

@SpringBootApplication
@MapperScan("com.winter.dao")
public class SpringbootMybatisDemoApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisDemoApplication.class, args);
    }

你可能感兴趣的:(高级框架,Mybatis知识点,mybatis)