MyBatis05(不写mapper.xml 直接在mapper上注解)

目录结构:

MyBatis05(不写mapper.xml 直接在mapper上注解)_第1张图片

1.配置mybatis-config.xml:
































 

2.log4j日志和数据库jdbc文件、配置mybatis的util、实体类Student同mybatis03一样。https://blog.csdn.net/qq_33371766/article/details/80382010

 

3.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.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 findStudents();

}

 

4.测试类:StudentTest


 

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.mappers.StudentMapper;
import com.model.Student;
import com.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 studentList=studentMapper.findStudents();
for(Student student:studentList){
System.out.println(student);
}
}
}

所需jar:

MyBatis05(不写mapper.xml 直接在mapper上注解)_第2张图片

 

你可能感兴趣的:(笔记)