在方法前使用注解的方式
绑定接口到核心配置文件中:
本质:使用反射
底层:动态代理
使用注解进行增删改查:
自动提交事务:
工具类:
public interface UserMapper {
@Select("select * from user")
//获取全部用户
ListgetUser();
// ---------------------------------------------
//方法存在多个参数,所有的参数前面必须加上@Param("")
@Select("select * from user where id=#{id}")
//获取id获取用户
User getUserById(@Param("id") int id);
// ------------------------------------------------
@Insert("insert into user(id,name,pwd) values(#{id},#{name},#{pwd})")
int addUser(User user);
// ---------------------------------------------------
@Update("update user set name=#{name},pwd=#{pwd} where id=#{id}")
int updateUser(Mapmap);
//------------------------------------------------------
@Delete("delete from user where id=#{id}")
int deleteUser(@Param("id")int id);
}
public class User {
private int id;
private String name;
private String pwd;
getter setter tostring;
}
测试类
@Test
public void getUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List user = mapper.getUser();
for (User user1 : user) {
System.out.println(user1);
}
sqlSession.close();
}
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userById = mapper.getUserById(2);
System.out.println(userById);
sqlSession.close();
}
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(6,"哈哈哈是的","76543"));
sqlSession.close();
}
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap map = new HashMap<>();
map.put("id",2);
map.put("name","2two");
map.put("pwd","lasf");
mapper.updateUser(map);
sqlSession.close();
}
@Test
public void delete(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(2);
sqlSession.close();
}
Mybatis详细执行流程:
-
Resource获取全局配置文件
-
实例化SqlsessionFactoryBuilder
-
解析配置文件流XMLCondigBuilder
-
Configration所有的配置信息
-
SqlSessionFactory实例化
-
trasactional事务管理
-
创建executor执行器
-
创建SqlSession
-
实现CRUD
-
查看是否执行成功
-
提交事务
-
关闭
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)