本博客项目结构
其中做了很多调整 重点的是,更新了MybatisUtils类:
使用注解开发
使用注解来映射简单语句会使代码显得更加简洁,然而对于稍微复杂一点的语句,Java注解就力不从心了,并且会显得更加混乱。因此,如果你需要完成很复杂的事情,那么最好使用XML映射语句。
注意:利用注解开发就不需要mapper.xml映射文件了 .
0. 注意User有个属性名与数据库中的不一致
1.在mybatis的核心配置文件中注入
<mappers>
<mapper class="com.kuang.mapper.UserMapper"/>
</mappers>
不再是resources,因为不是.xml文件
2.在UserMapper接口中添加注解
public interface UserMapper {
@Select("select id,name,pwd password2 from user")
public List<User> getAllUser();
@Select("select * from user where id = #{id}")
User selectUserById(@Param("id") int id);
@Insert("insert into user (id,name,pwd) values (#{id},#{name},#{password2})")
int addUser(User user);
@Update("update user set name=#{name},pwd=#{password2} where id = #{id}")
int updateUser(User user);
@Delete("delete from user where id = #{id}")
int deleteUser(@Param("id")int id);
}
3. 编写测试TestAnnotation类
public class TestAnnotation {
@Test
public void testGetAllUser() {
SqlSession session = MybatisUtils.getSqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> users = mapper.getAllUser();
for (User user : users){
System.out.println(user);
}
session.close();
}
@Test
public void testSelectUserById() {
SqlSession session = MybatisUtils.getSqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.selectUserById(1);
System.out.println(user);
session.close();
}
@Test
public void testAddUser() {
SqlSession session = MybatisUtils.getSqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = new User(6, "秦疆", "123456");
mapper.addUser(user);
session.close();
}
@Test
public void testUpdateUser() {
SqlSession session = MybatisUtils.getSqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = new User(6, "秦疆", "zxcvbn");
mapper.updateUser(user);
session.close();
}
@Test
public void testDeleteUser() {
SqlSession session = MybatisUtils.getSqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
mapper.deleteUser(6);
session.close();
}
}
# {}与’${}'的区别
-
#{} 的作用主要是替换预编译语句(PrepareStatement)中的占位符? 【推荐使用】 INSERT INTO user (name) VALUES (
INSERT INTO user (name) VALUES (?);
-
${} 的作用是直接进行字符串替换 INSERT INTO user (name) VALUES ('${name}');
INSERT INTO user (name) VALUES ('kuangshen');
|