使用步骤
1.在接口中注解
public interface UserMapper {
@Select("select * from mybatis.user")
List<User> getUserList();
}
2.在mybatis-config.xml中绑定
<mappers>
<mapper class="com.geng.dao.UserMapper"/>
</mappers>
3.测试
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
}
测试结果
本质:反射机制实现
底层:动态代理
注解实现增删查改
UserMapper.java
package com.geng.dao;
import com.geng.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
// 查询
@Select("select * from mybatis.user")
List<User> getUserList();
// 根据id查询
@Select("select * from mybatis.user where id=#{id}")
User getUserById(@Param("id") int id);
// 增加
@Insert("insert into mybatis.user (id,name,pwd) values(#{id},#{name},#{pwd})")
int addUser(User user);
// 修改
@Update("update mybatis.user set name=#{name}, pwd=#{pwd} where id = #{id}")
int updateUser(User user);
// 删除
@Delete("delete from mybatis.user where id=#{id}")
int deleteUser(@Param("id")int id);
}
UserDaoTest.java
import com.geng.dao.UserMapper;
import com.geng.pojo.User;
import com.geng.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void selectTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void selectByIdTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(2);
System.out.println(user);
sqlSession.close();
}
@Test
public void insertTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(1, "gengsj", "22222"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(1, "doudou", "33333"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(4);
sqlSession.commit();
sqlSession.close();
}
}
2021.6.6 上海漕河泾