Mybatis注解注解方式动态SQL
@InsertProvider
@UpdateProvider
@DeleteProvider
@SelectProvider
1.编写jdbc.properties,log4j.properties,mybatis-config.xml
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_mybatis
jdbc.username=root
jdbc.password=123456
log4j.rootLogger=info,appender1,appender2
log4j.appender.appender1=org.apache.log4j.ConsoleAppender
log4j.appender.appender2=org.apache.log4j.FileAppender
log4j.appender.appender2.File=C:/logFile.txt
log4j.appender.appender1.layout=org.apache.log4j.TTCCLayout
log4j.appender.appender2.layout=org.apache.log4j.TTCCLayout
<configuration>
<properties resource="jdbc.properties"/>
<typeAliases>
<package name="com.newbeedaly.model"/>
typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
dataSource>
environment>
<environment id="test">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
dataSource>
environment>
environments>
<mappers>
<package name="com.newbeedaly.mappers"/>
mappers>
configuration>
2.编写SqlSessionFactoryUtil类
package com.newbeedaly.util;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class SqlSessionFactoryUtil {
private static SqlSessionFactory sqlSessionFactory;
public static SqlSessionFactory getSqlSessionFactory(){
if(sqlSessionFactory==null){
InputStream inputStream=null;
try{
inputStream=Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
}catch(Exception e){
e.printStackTrace();
}
}
return sqlSessionFactory;
}
public static SqlSession openSession(){
return getSqlSessionFactory().openSession();
}
}
3.编写Mapper和动态Mapper类
package com.newbeedaly.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.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.UpdateProvider;
import com.newbeedaly.model.Student;
public interface StudentMapper {
@InsertProvider(type=StudentDynaSqlProvider.class,method="insertStudent")
public int insertStudent(Student student);
@UpdateProvider(type=StudentDynaSqlProvider.class,method="updateStudent")
public int updateStudent(Student student);
@DeleteProvider(type=StudentDynaSqlProvider.class,method="deleteStudent")
public int deleteStudent(int id);
@SelectProvider(type=StudentDynaSqlProvider.class,method="getStudentById")
public Student getStudentById(Integer id);
@SelectProvider(type=StudentDynaSqlProvider.class,method="findStudents")
public List findStudents(Map map);
}
package com.newbeedaly.mappers;
import java.util.Map;
import org.apache.ibatis.jdbc.SQL;
import com.newbeedaly.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();
}
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();
}
public String deleteStudent(){
return new SQL(){
{
DELETE_FROM("t_student");
WHERE("id=#{id}");
}
}.toString();
}
public String getStudentById(){
return new SQL(){
{
SELECT("*");
FROM("t_student");
WHERE("id=#{id}");
}
}.toString();
}
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();
}
}
4.编写Student类
package com.newbeedaly.model;
public class Student {
private Integer id;
private String name;
private Integer 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 Student(String name, Integer age) {
super();
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 + "]";
}
}
5.编写测试类
package com.newbeedaly.service;
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.newbeedaly.mappers.StudentMapper;
import com.newbeedaly.model.Student;
import com.newbeedaly.util.SqlSessionFactoryUtil;
public class StudentTest {
private static Logger logger=Logger.getLogger(StudentTest.class);
private SqlSession sqlSession=null;
private StudentMapper studentMapper=null;
/**
* 测试方法前调用
* @throws Exception
*/
@Before
public void setUp() throws Exception {
sqlSession=SqlSessionFactoryUtil.openSession();
studentMapper=sqlSession.getMapper(StudentMapper.class);
}
/**
* 测试方法后调用
* @throws Exception
*/
@After
public void tearDown() throws Exception {
sqlSession.close();
}
@Test
public void testInsert() {
logger.info("添加学生");
Student student=new Student("琪琪",11);
studentMapper.insertStudent(student);
sqlSession.commit();
}
@Test
public void testUpdate() {
logger.info("更新学生");
Student student=new Student(6,"琪琪2",12);
studentMapper.updateStudent(student);
sqlSession.commit();
}
@Test
public void testDelete() {
logger.info("删除学生");
studentMapper.deleteStudent(6);
sqlSession.commit();
}
@Test
public void testGetById() {
logger.info("通过ID查找学生");
Student student=studentMapper.getStudentById(1);
System.out.println(student);
}
@Test
public void testFindStudents() {
logger.info("查找所有学生");
Map map=new HashMap();
// map.put("name", "%张%");
// map.put("age", 12);
List studentList=studentMapper.findStudents(map);
for(Student student:studentList){
System.out.println(student);
}
}
}