Mybatis注解CRUD
1、CRUD
我们可以在工具类创建的时候实现自动提交事务!
public class MybatisUtils{
private static SqlSessionFactory sqlSessionFactory;
static{
try{
//使用Mybatis第一步:获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch(IOException e){
e.printStackTrace();
}}public static sqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}}
2.编写接口
public interface UserMapper{
@Select("select * from user")
List getUsers();
@Select("select * from user where id=#{id}")
User getUserById(@Param("id") int id);
@Insert("insert into user(id,name,pwd) values(#{id},#{name},#{pwd})")
int addUser(User user);
@Update("update user set name=#{name},pwd=#{pwd} where id=#{id}")
int updateUser(User user);
@Delete(delete from user where id=#{uid})
int deleteUser(@Param("uid") int id);
}
3.编写核心配置文件
【注意:我们必须要将接口注册绑定到我们的核心配置文件中!】
关于@Param("xxx")注解
- 基本类型的参数或者String类型,需要加上
- 引用类型不需要加
- 如果只有一个基本类型的话,可以忽略,但是建议加上!
- 我们在SQL中引用的就是@Param("xxx")中设定的属性名!
- #{}表示一个占位符号,通过#{}可以实现preparedStatement向占位符中设置值,自动
进行java类型和jdbc类型转换。
- #{}可以有效防止sql注入。
- #{}可以接收简单类型值或pojo属性值。 如果parameterType传输单个简单类型值,#{}括号中可以是value或其它名称。
- ${}表示拼接sql串,通过${}可以将parameterType 传入的内容拼接在sql中且不进行
jdbc类型转换
- ${}可以接收简单类型值或pojo属性值,如果parameterType传输单个简单类型值,${}括号中只能是value。
推荐阅读
- 关于QueryWrapper|关于QueryWrapper,实现MybatisPlus多表关联查询方式
- mybatisplus如何在xml的连表查询中使用queryWrapper
- mybatisplus|mybatisplus where QueryWrapper加括号嵌套查询方式
- MybatisPlus|MybatisPlus LambdaQueryWrapper使用int默认值的坑及解决
- MybatisPlus使用queryWrapper如何实现复杂查询
- SpringBoot调用公共模块的自定义注解失效的解决
- 生活与游戏日记(第182篇)(〔成长瞬间〕关注解决问题2019.10)
- Spring|Spring Boot 自动配置的原理、核心注解以及利用自动配置实现了自定义 Starter 组件
- Spring注解驱动第十讲--@Autowired使用
- =======j2ee|spring用注解实现注入的@resource,@autowired,@inject区别