目录
mybatisTest下
- @Test
- public void test2() throws IOException {
- //模拟user对象
- User user=new User();
- user.setUsername("ZengHui");
- user.setPassword("1234");
-
- //获得核心配置文件
- InputStream resourceAsFile = Resources.getResourceAsStream("sqlMapConfig.xml");
- //获得session工厂对象
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsFile);
- //获得session会话对象
- SqlSession sqlSession = sqlSessionFactory.openSession();
- //执行操作 参数:namespace+id
- int result= sqlSession.insert("userMapper.insertUser",user);
- //mybatis默认不自动提交事务,提交后才能持久化到数据库中
- sqlSession.commit();
- System.out.println(result);
- //释放资源
- sqlSession.close();
-
- }
UserMapper.xml下
-
- <insert id="insertUser" parameterType="com_mybatis.pojo.User">
- insert into user values (#{id},#{username},#{password})
- insert>
运行结果
在UserMapper.xml文件下
- <update id="update" parameterType="com_mybatis.pojo.User">
- update user set username=#{username},password=#{password} where id=#{id}
- update>
MybatisTest类下
-
- @Test
- //修改操作
- public void test3() throws IOException {
- //模拟user对象
- User user=new User();
- user.setId(3);
- user.setUsername("ZhaoLiu");
- user.setPassword("12345");
-
- //获得核心配置文件
- InputStream resourceAsFile = Resources.getResourceAsStream("sqlMapConfig.xml");
- //获得session工厂对象
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsFile);
- //获得session会话对象
- SqlSession sqlSession = sqlSessionFactory.openSession();
- //执行操作 参数:namespace+id
- sqlSession.update("userMapper.update", user);
- //mybatis默认不自动提交事务,提交后才能持久化到数据库中
- sqlSession.commit();
-
- //释放资源
- sqlSession.close();
-
- }
运行之后,数据库中变化
userMapper.xml
- <delete id="delete" parameterType="java.lang.Integer">
- delete from user where id=#{id}
- delete>
mybatisTest类下
- @Test
- //删除
- public void test4() throws IOException {
-
- //获得核心配置文件
- InputStream resourceAsFile = Resources.getResourceAsStream("sqlMapConfig.xml");
- //获得session工厂对象
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsFile);
- //获得session会话对象
- SqlSession sqlSession = sqlSessionFactory.openSession();
- //执行操作 参数:namespace+id
- sqlSession.delete("userMapper.delete", 3);
- //mybatis默认不自动提交事务,提交后才能持久化到数据库中
- sqlSession.commit();
-
- //释放资源
- sqlSession.close();
-
- }
运行结果
删除语句使用delete标签
Sql语句中使你#{任意字符串}方式引用传递的单个参数
删除操作使用的API是sqlSession.delete("命名空间.id",Object)