Java———Mybaits常用的注解

一、注解实现简单数据查询。

1、不带参数的注解查询

Mapper接口中:

// 查询所有图书信息
@Select("select * from book")
List<Book> selectBookAll();

Test中:

// 
@Test
public void selectBookAll(){
    SqlSession session=MybatisUtil.getSession();  // 利用工具类创建SqlSession对象
    BookMapper bookMapper=session.getMapper(BookMapper.class);  // 获取mapper接口实例
    List<Book> bookList=bookMapper.selectBookAll();    //调用mapper接口的方法完成查询
    for(Book book : bookList){               
        System.out.println(book);        // 循环输出
    }

}

控制台测试结果:

Book{bookId=1, bookNo='9787517086543', bookName='Web前端开发入门与实战', author='刘兵', description='名师力作、彩色印刷,手机扫码看272集(52小时)同步视频讲解+235个实例源码分析+16个综合实验+2个项目实战+30个思维导图,手把手教你轻松学会Web前端开发,赠课后习题及答案等。', inputPrice=5.9, originalPrice=98.0, publisher='水利水电出版社', publishDate='2020年08月', bookTitle='Web前端开发 HTML5+CSS3+JavaScript+Vue.js+jQuery 网页设计 网页制作 网站建设自学教程教材书籍 web安全', isDown=0.0, storeCount=44, downDate=null, discount=1.0, categoryId=111}
Book{bookId=3, bookNo='9787302581260', bookName='Java从入门到精通', author='明日科技', description='Java入门经典,销售12年,80万Java程序员、数百所高校选择,210集教学视频+211个应用示例+151个编程训练+94个综合训练+海量开发资源库+在线答疑,Java核心技术,Java编程思想。', inputPrice=12.5, originalPrice=129.0, publisher='清华大学出版社', publishDate='2021年07月', bookTitle='Java从入门到精通(第6版)(软件开发视频大讲堂)', isDown=0.0, storeCount=149, downDate=null, discount=1.0, categoryId=112}

 2、带一个参数的注解查询。

Mapper接口:

// 根据主关键字查询图书信息
@Select("select * from book where bookId=#{bookId}")
Book selectBookById(int bookId);

Test:

@Test
public void selectBookById(){
    SqlSession session=MybatisUtil.getSession();  // 利用工具类创建SqlSession对象
    BookMapper bookMapper=session.getMapper(BookMapper.class);  // 获取mapper接口实例
    Book book=bookMapper.selectBookById(1);
    System.out.println(book);
}

控制台测试结果:

Book{bookId=1, bookNo='9787517086543', bookName='Web前端开发入门与实战', author='刘兵', description='名师力作、彩色印刷,手机扫码看272集(52小时)同步视频讲解+235个实例源码分析+16个综合实验+2个项目实战+30个思维导图,手把手教你轻松学会Web前端开发,赠课后习题及答案等。', inputPrice=5.9, originalPrice=98.0, publisher='水利水电出版社', publishDate='2020年08月', bookTitle='Web前端开发 HTML5+CSS3+JavaScript+Vue.js+jQuery 网页设计 网页制作 网站建设自学教程教材书籍 web安全', isDown=0.0, storeCount=44, downDate=null, discount=1.0, categoryId=111}

3、带多参数的注解查询。

Mapper接口:

// 查询指定的进价价格范围的图书信息。
@Select("select * from book where inputPrice between #{min} and #{max}")
List<Book> selectBookByInputPrice(@Param("min")double min,@Param("max")double max);

Test::

@Test
public void selectBookById(){
    SqlSession session=MybatisUtil.getSession();  // 利用工具类创建SqlSession对象
    BookMapper bookMapper=session.getMapper(BookMapper.class);  // 获取mapper接口实例
    List<Book> bookList=bookMapper.selectByInputPrice(20,40);
    for(Book book : bookList){
        System.out.println(book);
    }
}

控制台测试结果:

Book{bookId=4, bookNo='9787115508232', bookName='操作系统导论', author='雷姆兹·H·阿帕希杜塞尔', description='美国知名操作系统教材 紧紧围绕操作系统的三大主题元素--虚拟化 并发和持久性进行讲解', inputPrice=30.0, originalPrice=55.0, publisher='人民邮电出版社', publishDate='2019年06月', bookTitle='操作系统导论', isDown=0.0, storeCount=50, downDate=null, discount=1.0, categoryId=120}
Book{bookId=5, bookNo='9787111604365', bookName='操作系统概念', author='亚伯拉罕·西尔伯沙茨', description='Silberschatz操作系统经典教材,新增多核系统和移动计算的重要内容!', inputPrice=30.0, originalPrice=85.0, publisher='机械工业出版社', publishDate='2018年07月', bookTitle='操作系统概念(原书第9版)', isDown=0.0, storeCount=96, downDate=null, discount=1.0, categoryId=120}
Book{bookId=11, bookNo='9787115464699', bookName='JavaScript基础教程', author='莫振杰', description='Web前端开发精品课 JavaScript基础教程', inputPrice=20.0, originalPrice=49.0, publisher='人民邮电出版社', publishDate='2017年07月', bookTitle='Web前端开发精品课 JavaScript基础教程', isDown=0.0, storeCount=40, downDate=null, discount=1.0, categoryId=110}
Book{bookId=13, bookNo='9787121443299', bookName='Vue.js 3.0企业及管理后台开发实战', author='杨海民', description='400余个代码清单,配套资料丰富,快速掌握Vue.js。详解管理后台各业务模块及项目文件,全景还原企业内部项目开发过程,自主搭建管理后台。', inputPrice=40.0, originalPrice=72.0, publisher='电子工业出版社', publishDate='2022年11月', bookTitle='Vue.js 3.0企业级管理后台开发实战:基于Element Plus', isDown=0.0, storeCount=300, downDate=null, discount=1.0, categoryId=111}

注意:上述多参数查询参数类型也可以用Map格式来接收参数,SQL语句中的between and 是闭区间范围。

二、注解实现结果映射的查询:实体类若某个属性名和查询结果的字段名称不一致,则需要使用结果映射。

1、一对多的注解查询查询所有三级图书分类以及该分类对应的图书信息。

分析:图书分类为一端,图书为多端,一对多查询在一端进行结果映射。

Mapper接口:

 (1)图书Mapper接口:

@Select("select * from book where categoryId=#{categoryId}")
List<Book> selectByCategoryId(int categoryId);

 (2)图书分类Mapper接口:

@Select("select * from category where level=3")
@Results({
    @Result(property="categoryId",column="categoryId",id=true),
    @Result(property="bookList",column="categoryId",many=@Many(select="com.mappers.BookMapper.selectByCategoryId"))
})       
List<BookAndCategoryVo> selectAll();  // List泛型中BookAndCategory类为查询结果所需要的结果类

Test:

@Test
public void selectAll() {
   SqlSession session= MybatisUtil.getSqlSession();
   CategoryMapper categoryMapper=session.getMapper(CategoryMapper.class);
   List<CategoryAndBookVo> categoryAndBookVos=categoryMapper.selectAll();
   for (CategoryAndBookVo categoryAndBookVo : categoryAndBookVos) {
       System.out.println(categoryAndBookVo);
   }
}

控制台测试结果:

CategoryAndBookVo{categoryId=112, categoryName='Java基础', bookList=[Book{bookId=3, bookNo='9787302581260', bookName='Java从入门到精通', author='明日科技', description='Java入门经典,销售12年,80万Java程序员、数百所高校选择,210集教学视频+211个应用示例+151个编程训练+94个综合训练+海量开发资源库+在线答疑,Java核心技术,Java编程思想。', inputPrice=12.5, originalPrice=129.0, publisher='清华大学出版社', publishDate='2021年07月', bookTitle='Java从入门到精通(第6版)(软件开发视频大讲堂)', isDown=0.0, storeCount=149, downDate=null, discount=1.0, categoryId=112}]}
CategoryAndBookVo{categoryId=115, categoryName='PHP基础', bookList=[Book{bookId=12, bookNo='9787569208689', bookName='零基础学PHP', author='明日科技', description='10万读者认可的编程图书,零基础自学编程的入门图书,循序渐进,详解PHP语言的编程思想和核心技术,配同步视频教程和源代码,海量资源免费赠送', inputPrice=11.0, originalPrice=30.0, publisher='吉林大学出版社', publishDate='2017年09月', bookTitle='零基础学PHP(全彩版)', isDown=0.0, storeCount=30, downDate=null, discount=1.0, categoryId=115}]}

小结:

  (1)上述@Result中的property属性指目标类的哪个属性需要进行结果映射。

  (2)上述@Result中的column属性指查询结果中的哪个字段于相对应。

  (3)上述@Result中的id属性取值为逻辑值

  (4)@Many,用于一对多的关系映射

2、一对一的注解查询:查询班主任对应的班级

班级Mapper:

@Select("select * from classmate where tid=#{tid}")
Classmate selectByTid(int tid);

班主任Mapper:

@Select("select * from teacher")
@Results({
    @Result(property="teacher.tid",column="tid",id=true),
    @Result(property="teacher.teacherName",column="teacherName"),
    @Result(property="teeacher.sex",column="sex"),
    @Result(property="teacher.age",column="age"),
    @Result(property="classmate",column="tid",one=@One(select="com.mappers.ClassmateMapper.selectByTid"))
})
List<TeacherAndClassmateVo> selectAll();

Test:

@Test
public void selectAll() {
   SqlSession session= MybatisUtil.getSqlSession();
   TeacherMapper teacherMapper=session.getMapper(TeacherMapper.class);
   List<TeacherAndClassmateVo> teacherAndClassmateVos=teacherMapper.selectAll();
   for (TeacherAndClassmateVo teacherAndClassmateVo : teacherAndClassmateVos) {
       System.out.println(teacherAndClassmateVo);
   }
}

控制台测试结果:

TeacherAndClassmateVo{teacher=Teacher{tid=1, teacherName='张胖一号', sex='男', age=38}, classmate=Classmate{classmateId=1, classmateName='高一一班', total=35, tid=1}}
TeacherAndClassmateVo{teacher=Teacher{tid=2, teacherName='张胖二号', sex='女', age=36}, classmate=Classmate{classmateId=2, classmateName='高二二班', total=38, tid=2}}
TeacherAndClassmateVo{teacher=Teacher{tid=3, teacherName='张胖三号', sex='女', age=39}, classmate=Classmate{classmateId=3, classmateName='高一三班', total=29, tid=3}}

三、注解实现数据操纵语言

1、新增教师信息,并返回新增的主关键字。

Mapper:

@Insert("insert into teahcer values(null,#{teacherName},#{sex},#{age})")
@SelectKey(statement="select last_insert_id()",keyProperty="tid",keyColumn="tid",before=false,resultType=int.class)
int insertTeacher(Teacher teacher);

Test:

@Test
public void insertTeacher(){
    SqlSession session= MybatisUtil.getSqlSession();
    TeacherMapper teacherMapper=session.getMapper(TeacherMapper.class);
    Teacher teacher=new Teacher();
    teacher.setTeacherName("张三");
    teacher.setSex("男");
    teacher.setAge(25);
    int n=teacherMapper.insertTeacher(teacher);
    session.commit();
    System.out.println(teacher.getTid());
}

控制台测试结果:

24ee984a65a24ad4ac19b0a4ab3fd44d.png

 22c475015e3340b9a2bf4b903155c68a.png

 上述看控制台输出了新增数据的主关键字,数据库结果也已经新增进去。

 小结:@SelectKey是新增后向对象中填充新增记录的主关键字的。

        SelectKey属性:

        (1)statement:指注入主关键字字段的内容用哪个SQL语句得到。

        (2)keyProperty:指定实体类中的哪个属性接收注入的结果。

        (3)keyColumn:指定数据表中的哪个字段注入至类的属性中。

        (4)before:设置本操作在@Insert()注解之前执行吗?取值为布尔型。

        (4)resultType:设置注入的结果的数据类型。

2、修改教师信息

Mapper:

@Update("update teacher set teacherName=#{teacherName},sex=#{sex},age=#{age} where tid=#{tid}")
int updateTeacher(Teacher taeacher);

Test:

@Test
public void updateTeacher(){
  SqlSession session= MybatisUtil.getSqlSession();
  TeacherMapper teacherMapper=session.getMapper(TeacherMapper.class);
  Teacher teacher=new Teacher();
  teacher.setTid(7);
  teacher.setTeacherName("李四");
  teacher.setSex("男");
  teacher.setAge(33);
  int n=teacherMapper.updateTeacher(teacher);
  session.commit();
}

执行后数据库结果:

f7f650e4c9e0434b8f3c164a3766fd81.png

 3、删除教师信息

Mapper:

@Delete("delete from teacher where tid=#{tid}")
int deleteTeacher(int tid);

Test:

@Test
public void deleteTeacher(){
    SqlSession session= MybatisUtil.getSqlSession();
    TeacherMapper teacherMapper=session.getMapper(TeacherMapper.class);
    int n=teacherMapper.deleteTeacher(7);
    System.out.println(n);
    session.commit();
}

执行后数据库结果就没了。

总结:在实际开发中注解的方式用的还是方便,但是mapper.xml文件还是可以用的,有的复杂查询还是需要用XML文件的。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值