使用注解配置SQL映射器
缺点:方便
优点:不够灵活,不支持所有的功能
第一节:基本映射语句
1,@Insert
2,@Update
3,@Delete
4,@Select
第二节:结果集映射语句
@Results
项目代码:https://download.csdn.net/download/chpllp/10617826
StudentTest.java
package com.java1234.service;
import java.util.List;
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.java1234.mappers.StudentMapper;
import com.java1234.model.Student;
import com.java1234.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("琪琪", 11);
studentMapper.insertStudent(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(5);
System.out.println(student.toString());
}
@Test
public void testFindStudents() {
logger.info("查找所有学生");
List<Student> studentList = studentMapper.findStudents();
for(Student student:studentList)
System.out.println(student.toString());
}
}
StudentMapper.java
package com.java1234.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.java1234.model.Student;
public interface StudentMapper {
@Insert("insert into t_student values(null, #{name}, #{age})")
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<Student> findStudents();
}