一、注解开发
在面向接口开发中,我们可以在接口中声明方法,然后通用配置其对应的SQL映射文件来实现增删改查,当我们面对一些简单的SQL语句时,还有一种更简单的开发方式,那就是通过注解开发,省略掉SQL映射文件。
使用注解开发:
public interface EmployeeMapperAnnotation {
@Select("select * from tbl_employee")
public List<Employee> getEmps();
@Select("select * from tbl_employee where id=#{id}")
public Employee getEmpById(Integer id);
@Insert("insert into tbl_employee(`last_name`, `email`, `gender`) values(#{lastName}, #{email}, #{gender})")
public int addEmp(Employee emp);
@Update("update tbl_employee set `last_name` = #{lastName}, `email` = #{email}, `gender` = #{gender} where id = #{id}")
public int update(Employee emp);
@Delete("delete from tbl_employee where id = #{id}")
public int deleteEmp(Integer id);
}
测试:
public SqlSessionFactory getsqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
return sqlSessionFactory;
}
/**
* 注解方式
* @throws IOException
*/
@Test
public void testAnnotation() throws IOException {
//1、获取 sqlSessionFactory
SqlSessionFactory sqlSessionFactory = getsqlSessionFactory();
//2、获取 sqlSession 实例,能直接执行已经映射的 SQL 语句
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
//3、获取接口的实现类对象
EmployeeMapperAnnotation mapper = sqlSession.getMapper(EmployeeMapperAnnotation.class);
List<Employee> emps = mapper.getEmps();
System.out.println("---查询列表信息---");
emps.forEach(System.out::println);
Employee emp = mapper.getEmpById(1);
System.out.println("---查询员工号为1的信息:---");
System.out.println(emp);
int i = mapper.addEmp(new Employee(null, "Tom", "1", "Tom@126.com"));
System.out.println("插入数据后结果为:" + i);
int j = mapper.update(new Employee(21, "Jerry", "0", "Jerry@126.com"));
System.out.println("更新数据后结果为:" + j);
mapper.deleteEmp(4);
sqlSession.commit();
} finally {
sqlSession.close();
}
}
对于简单的 SQL 语句,可以直接使用注解进行开发,也可以结合注解与配置文件一起使用,但还是建议使用配置文件的方式,这样可以防止硬编码,实现解耦。