MyBatis3使用注解配置SQL映射器

阅读更多
1. MyBatis3使用注解配置SQL映射器

新建MyBatisPro03项目


package com.andrew.mappers;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.andrew.model.Student;
public interface StudentMapper {
    @Insert("insert into t_student values(null,#{name},#{age},1,1,1,1)")
    public int insertStudent(Student student);
    @Update("update t_student set name=#{name},age=#{age} where id=#{id}")
    public int updateStudent(Student student);
    @Delete("delete from t_student where id=#{id}")
    public int deleteStudent(int id);
    @Select("select * from t_student where id=#{id}")
    public Student getStudentById(Integer id);
    @Select("select * from t_student")
    @Results({
        @Result(id=true,column="id",property="id"),
        @Result(column="name",property="name"),
        @Result(column="age",property="age")
    })
    public List findStudents();
}


package com.andrew.service;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.andrew.mappers.StudentMapper;
import com.andrew.model.Student;
import com.andrew.util.SqlSessionFactoryUtil;
public class StudentAnnotationTest {
    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() {
        Student student = new Student("琪琪",11);
        studentMapper.insertStudent(student);
        sqlSession.commit();
    }
    @Test
    public void testUpdate() {
        Student student = new Student(16, "琪琪2", 12);
        studentMapper.updateStudent(student);
        sqlSession.commit();
    }
    @Test
    public void testDelete() {
        studentMapper.deleteStudent(16);
        sqlSession.commit();
    }
    @Test
    public void testGetById() {
        Student student = studentMapper.getStudentById(1);
        System.out.println(student);
    }
    @Test
    public void testFindStudents() {
        List studentList = studentMapper.findStudents();
        for (Student student : studentList) {
            System.out.println(student);
        }
    }
}

你可能感兴趣的:(mybatis)