J2EE系列之MyBatis学习笔记(十二)-- 使用注解配置sql映射器
来源:互联网 发布:php有线程吗? 编辑:程序博客网 时间:2024/06/05 03:02
这一节讲述使用注解方式实现动态sql。所谓的动态sql就是动态的拼接sql语句,之前讲过使用xml文件方式进行配置,这里讲述使用注解方式进行动态拼接。
1.新建工程MyBatisPro04,按照之前的配置配置好。
2.我们这里只使用Student一个类。新建Student类:
package com.test.model;public class Student {private Integer id;private String name;private Integer age;public Student(String name, Integer age) {super();this.name = name;this.age = age;}public Student() {super();// TODO Auto-generated constructor stub}public Student(Integer id, String name, Integer age) {super();this.id = id;this.name = name;this.age = age;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";}}
3.新建接口StudentMapper:
package com.test.mappers;import java.util.List;import java.util.Map;import org.apache.ibatis.annotations.DeleteProvider;import org.apache.ibatis.annotations.InsertProvider;import org.apache.ibatis.annotations.SelectProvider;import org.apache.ibatis.annotations.UpdateProvider;import com.test.model.Student;public interface StudentMapper {public int insertStudent(Student student);public int updateStudent(Student student);public int deleteStudent(int id);public Student getStudentById(Integer id);public List<Student> findStudents(Map<String,Object> map);}
这里有插入、修改、删除、查找单个、查找所有学生的方法接口。
3.要想使用注解的方式实现动态sql,需要新建另外一个动态sql语句拼接类。在com.test.mappers包中新建类StudentDynaSqlProvider:
package com.test.mappers;
import java.util.Map;
import org.apache.ibatis.jdbc.SQL;
import com.test.model.Student;
public class StudentDynaSqlProvider {
public String insertStudent(final Student student){
return new SQL(){
{
INSERT_INTO("t_student");
if(student.getName()!=null){
VALUES("name", "#{name}");
}
if(student.getAge()!=null){
VALUES("age", "#{age}");
}
}
}.toString();
}
}
这个类中的insertStudent方法实现了动态拼接插入学生的sql语句,并把这个拼接的sql语句返回。由于涉及到匿名内部类,传入的形参是final类型的。
4.上面完成了插入学生的sql语句的动态拼接,接下来就要使用注解来实现插入学生的时候调用这个方法。修改StudentMapper如下:
package com.test.mappers;import java.util.List;import java.util.Map;import org.apache.ibatis.annotations.DeleteProvider;import org.apache.ibatis.annotations.InsertProvider;import org.apache.ibatis.annotations.SelectProvider;import org.apache.ibatis.annotations.UpdateProvider;import com.test.model.Student;public interface StudentMapper {@InsertProvider(type=StudentDynaSqlProvider.class,method="insertStudent")public int insertStudent(Student student);public int updateStudent(Student student);public int deleteStudent(int id);public Student getStudentById(Integer id);public List<Student> findStudents(Map<String,Object> map);}
这里在insertStudent方法上面添加了注解@InsertProvider(type=StudentDynaSqlProvider.class,method="insertStudent"),表示调用insertStudent方法的时候去调用StudentDynaSqlProvider中的insertStudent方法来动态的拼接sql语句。
5.写测试方法:
package com.test.service;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.ibatis.session.SqlSession;import org.apache.log4j.Logger;import org.junit.After;import org.junit.Before;import org.junit.Test;import com.test.mappers.StudentMapper;import com.test.model.Student;import com.test.util.SqlSessionFactoryUtil;public class StudentTest {private static Logger logger = Logger.getLogger(StudentTest.class);private SqlSession sqlSession = null;private StudentMapper studentMapper = null;@Beforepublic void setUp() throws Exception {sqlSession = SqlSessionFactoryUtil.openSession();studentMapper = sqlSession.getMapper(StudentMapper.class);}@Afterpublic void tearDown() throws Exception {sqlSession.close();}@Testpublic void testInsert() {logger.info("注解方式添加学生");Student student = new Student("小七",17);studentMapper.insertStudent(student);sqlSession.commit();}}
运行测试方法testInsert,在数据库中插入了相应的数据。
6.添加修改学的的动态拼接sql语句实现:
public String updateStudent(final Student student){return new SQL(){{UPDATE("t_student");if(student.getName()!=null){SET("name=#{name}");}if(student.getAge()!=null){SET("age=#{age}");}WHERE("id=#{id}");}}.toString();}
添加注解:
@UpdateProvider(type=StudentDynaSqlProvider.class,method="updateStudent")public int updateStudent(Student student);
添加测试方法:
@Testpublic void testUpdate() {logger.info("注解方式更新学生");Student student = new Student(8,"小七2",20);studentMapper.updateStudent(student);sqlSession.commit();}
运行测试方法,数据库中相应信息得到了修改。
7.添加删除学生动态sql拼接方法实现:
public String deleteStudent(){return new SQL(){{DELETE_FROM("t_student");WHERE("id=#{id}");}}.toString();}
添加注解:
@DeleteProvider(type=StudentDynaSqlProvider.class,method="deleteStudent")public int deleteStudent(int id);
添加测试方法:
@Testpublic void testDelete() {logger.info("注解方式删除学生");studentMapper.deleteStudent(8);sqlSession.commit();}
运行测试方法,成功的删除了相应的学生信息。
8.添加查找单个学生动态sql拼接方法实现:
public String getStudentById(){return new SQL(){{SELECT("*");FROM("t_student");WHERE("id=#{id}");}}.toString();}
添加注解:
@SelectProvider(type=StudentDynaSqlProvider.class,method="getStudentById")public Student getStudentById(Integer id);
添加测试方法:
@Testpublic void testFindById() {logger.info("查找学生");Student student = studentMapper.getStudentById(1);System.out.println(student);}
运行测试方法,查询到了相应学生的信息。
9.上面介绍的都是简单的操作。下面来一个多条件查询,添加动态拼接sql实现:
public String findStudents(final Map<String,Object> map){return new SQL(){{SELECT("*");FROM("t_student");StringBuffer sb=new StringBuffer();if(map.get("name")!=null){sb.append(" and name like '"+map.get("name")+"'");}if(map.get("age")!=null){sb.append(" and age="+map.get("age"));}if(!sb.toString().equals("")){WHERE(sb.toString().replaceFirst("and", ""));}}}.toString();这里重点注意,通过map把查询条件传入到方法中,里面通过StringBuffer类来动态的拼接多个条件。最后一句,只有在输入条件不为空的情况下才能添加where子句。
添加注解:
@SelectProvider(type=StudentDynaSqlProvider.class,method="findStudents")public List<Student> findStudents(Map<String,Object> map);
添加测试方法:
@Testpublic void testFindStudents() {logger.info("查找所有学生");Map<String,Object> map = new HashMap<String,Object>();map.put("name", "%李%");map.put("age", 11);List<Student> studentList = studentMapper.findStudents(map);for(Student s:studentList){System.out.println(s);}}
运行测试方法,查询到了所有满足条件的学生信息。
这种使用注解方式的动态sql只需要了解,以后要使用xml配置的方式。使用注解 的方式非常的不灵活。
- J2EE系列之MyBatis学习笔记(十二)-- 使用注解配置sql映射器
- J2EE系列之MyBatis学习笔记(十)-- 使用注解配置sql映射器
- J2EE系列之MyBatis学习笔记(十一)-- 使用注解配置sql映射器
- J2EE系列之MyBatis学习笔记(三)-- 使用XML配置SQL映射器
- MyBatis学习笔记(六)--使用注解配置SQL映射器
- J2EE系列之MyBatis学习笔记(二)-- mybatis配置
- J2EE系列之MyBatis学习笔记(四)-- mybatis关系映射(一对一映射)
- J2EE系列之MyBatis学习笔记(五)-- mybatis关系映射(一对多映射)
- J2EE系列之MyBatis学习笔记(六)-- 动态sql
- J2EE系列之MyBatis学习笔记(七)-- 动态sql
- J2EE系列之Hibernate4学习笔记(十二)--Hibernate继承关系映射(每个类对应一个表)
- MyBatis学习笔记(三)--使用XML配置SQL映射器
- J2EE系列之Hibernate4学习笔记(十三)-- -一对一映射
- J2EE系列之Struts2学习笔记(十二)--自定义拦截器
- J2EE系列之MyBatis学习笔记(一)-- 简介
- J2EE系列之MyBatis学习笔记(八)-- 杂项
- J2EE系列之MyBatis学习笔记(九)-- 杂项
- MyBatis学习笔记(十)注解映射
- 63_常用类_包装类_Integer_Number_JDK源码分析
- SNMP协议详解
- PL/SQL Developer官方下载地址
- Handler,使用PostDelayed延迟执行任务
- 网络缓存
- J2EE系列之MyBatis学习笔记(十二)-- 使用注解配置sql映射器
- online的操作介绍
- 2017年成为全栈开发工程师的权威指南
- 关于 WEB/HTTP 调试利器 Fiddler 的一些技巧分享
- C++模板详细整理2
- const在函数和方法上的防修改作用
- 【mysql】mysql获取两个集合的交集/差集/并集
- C#链接操作Access数据库
- FFMpeg所有命令行参数