MyBatis:注解开发

使用注解开发可以完全省略掉XXXMapper.xml文件
UserMapper(接口)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public interface UserMapper {

@Select("select * from user")
List<User> getUser();

@Select("select * from user where id = #{id}")
User getUserById(@Param("id") int id);

// 与实体类属性保持一致,虽然数据库里的字段是pwd,但是实体类中是password所以#{password}
@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password})")
int addUser(User user);

@Update("update user set name=#{name},pwd=#{password} where id=#{id}")
int updateUser(User user);
}

Test.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class UserMapperTest {
@Test
public void getUserTest() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> user = mapper.getUser();
for (User user1 : user) {
System.out.println(user1);
}
}
@Test
public void getUserByIdTest() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userById = mapper.getUserById(1);
System.out.println(userById);
}
@Test
public void addUserTest() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(5,"leo","666"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateTest() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(1,"xiaoke","666"));
sqlSession.commit();
sqlSession.close();
}
}

注解开发的底层实现是应用反射。
但是这个例子中有个问题,实体类中是password但是数据库字段为pwd,获取数据时,pwd会为null,所以官网上说注解开发只适用于简单场景,如果场景复杂还是建议xml

#与$的区别

#{} 的作用主要是替换预编译语句(PrepareStatement)中的占位符?:

对于 : INSERT INTO user (name) VALUES (#{name}); ==> INSERT INTO user (name) VALUES (?);

${} 符号的作用是直接进行字符串替换:

对于 : INSERT INTO user (name) VALUES (‘${name}’); ==> INSERT INTO user (name) VALUES (‘tianshozhi’);

为了防止SQL注入,建议使用#{}.

关于@Param()注解

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需加
  • 如果只有一个基本类型的话,可以忽略,但是建议大家都加上
  • 我们在SQL中引用的就是我们这里@Param()中设定的属性名
    例如
    1
    2
    @Select("select * from user where id = #{id}")
    User getUserById(@Param("id") int id);

如果吧@Param改成(“id2”),上面的#{}也要改:

1
2
@Select("select * from user where id = #{id2}")
User getUserById(@Param("id2") int id);