标签:imp std where res oid sel model .sql ibatis
1.在接口上注解sql
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();
}
2.测试:
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;
/**
* 测试方法前调用
* @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("查找所有学生");
List<Student> studentList=studentMapper.findStudents();
for(Student student:studentList){
System.out.println(student);
}
}
}
标签:imp std where res oid sel model .sql ibatis
原文地址:http://www.cnblogs.com/csy666/p/6536702.html