作者:c72586051 | 来源:互联网 | 2023-10-12 12:20
MyBatis 的真正强大在于它的语句映射,这是它的魔力所在。
创建接口 public interface UserInfoMapper {/*** 查找:* 查找所有用户* 根据id查找单个用户* @return*/List selectAllUsers();UserInfo selectUserById(Long userId);//新增一条数据Integer insetUserInfo(UserInfo userInfo);//根据id删除用户Integer deleteUserInfo(Long userId);//根据id修改用户名字Integer updateUserInfo( @Param("id") Long userId,@Param("name") String userName); }
接口创建完毕后更改mapper中的命名空间
配置映射 id与接口名需对应
select * from user_info select * from user_info where user_id=#{id} insert into user_info(username,user_password,create_time,update_time) values(#{userName},#{userPassword},now(),now()) delete from user_info where user_id=#{id} update user_info set username=#{name},update_time=now() where user_id=#{id}
注意传入多个参数情况,在接口处使用@Param(*)让其与#{*}对应
查 对sqlSession进行封装使得代码简洁
private static SqlSession getSqlSession() throws IOException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);return sqlSessionFactory.openSession();}
查找全部用户
public static void main( String[] args ) throws Exception{SqlSession sqlSession = getSqlSession();UserInfoMapper mapper=sqlSession.getMapper(UserInfoMapper.class);List userInfos=mapper.selectAllUsers();for (UserInfo userInfo : userInfos) {System.out.println(userInfo);}sqlSession.close();}
根据id查找某个用户
public static void main( String[] args ) throws Exception{SqlSession sqlSession = getSqlSession();UserInfoMapper mapper=sqlSession.getMapper(UserInfoMapper.class);UserInfo userInfo=mapper.selectUserById(1L);System.out.println(userInfo);sqlSession.close();}
增 public static void main( String[] args ) throws Exception{SqlSession sqlSession = getSqlSession();UserInfoMapper mapper=sqlSession.getMapper(UserInfoMapper.class);UserInfo userInfo=new UserInfo();userInfo.setUserName("wangwu");userInfo.setUserPassword("12345");mapper.insetUserInfo(userInfo);sqlSession.commit();sqlSession.close();}
删 public static void main( String[] args ) throws Exception{SqlSession sqlSession = getSqlSession();UserInfoMapper mapper=sqlSession.getMapper(UserInfoMapper.class);mapper.deleteUserInfo(3L);sqlSession.commit();sqlSession.close();}
改 public static void main( String[] args ) throws Exception{SqlSession sqlSession = getSqlSession();UserInfoMapper mapper=sqlSession.getMapper(UserInfoMapper.class);mapper.updateUserInfo(2L,"wangwu");sqlSession.commit();sqlSession.close();}
使用和指定语句的参数和返回值相匹配的接口(比如 BlogMapper.class),现在你的代码不仅更清晰,更加类型安全,还不用担心可能出错的字符串字面值以及强制类型转换。