您的位置:首页 > 数据库

J2EE系列之MyBatis学习笔记(十二)-- 使用注解配置sql映射器

2017-06-15 15:03 821 查看
这一节讲述使用注解方式实现动态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;
}
@Override
public 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;
@Before
public void setUp() throws Exception {
sqlSession = SqlSessionFactoryUtil.openSession();
studentMapper = sqlSession.getMapper(StudentMapper.class);
}

@After
public void tearDown() throws Exception {
sqlSession.close();
}

@Test
public 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);

添加测试方法:
@Test
public 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);

添加测试方法:
@Test
public 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);

添加测试方法:
@Test
public 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){

4000
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);

添加测试方法:
@Test
public 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配置的方式。使用注解 的方式非常的不灵活。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息