Mybatis测试增删改查----------Mybatis学习笔记(三)


2018/4/19    配置好了Mybatis的环境之后,接下来直接开始对增删改查进行测试.

1.建立一个数据库

CREATE TABLE category_ (
`id`  int NOT NULL AUTO_INCREMENT ,
`name`  varchar(255) NULL ,
PRIMARY KEY (`id`)
);    
 insert into category_ (name) values('萧敬腾');
 insert into category_ (name) values('德玛');
 insert into category_ (name) values('kh');
 insert into category_ (name) values('tom');
 insert into category_ (name) values('jack');

2.查询操

在com..kh.mybatis;新建一个TestSelect.java

根据mybatis的结构图来创建所需的sqlSession会话;

通过sqlSession来操作JDBC事务来操作数据库;

通过session.selectOne获取id=1的记录

Category cg= sqlSession.selectOne("FindById",1);
FindById对应的sql语句:
<select id="FindById" parameterType="int" resultType="Category">
select * from category_ where id= #{id}
</select>
package com.kh.mybatis;
 
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.kh.pojo.Category;
 
public class TestSelect {
    //根据id查询用户信息,得到一条记录结果
    public static void main(String[] args) throws IOException {
        //获得mybatis的环境配置文件
    	String resource="mybatis-config.xml";
        //以流的方式获取recource(mybatis的环境配置文件)
    	InputStream inputStream=Resources.getResourceAsStream(resource);
    	//创建会话工厂
    	SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
    	//通过工厂得到SqlSession
    	 SqlSession sqlSession= sqlSessionFactory.openSession();
    	//通过SqlSession操作数据库	
    	//selectOne 根据英语单词字面理解selectOne是只能查询出一条记录,也就是说返回结果为单条记录
        Category cg=sqlSession.selection("FindById",1);//这里的FindById就是在Category.xml中配置的<select id="FindById">
    	 System.out.println(cg);                     //Category.xml中的<select>标签的id名称不固定,顾名思义的起名字方便程序阅读
    	//释放资源
    	sqlSession.close();
    }
}



这里说一点:当查询结果为很多条的时候,我们使用:selectList(statement,pojo);来替代selectOne(statement,pojo);

在Category.xml文件中配置select的SQL语句,就可以映射到数据库中

 在<mapper>标签中写SQL标签

<mapper namespace="com.kh.pojo">
     <select id="FindById" parameterType="int" resultType="Category"> 
            select * from   category_  where id=#{id}      
     </select>
</mapper namespace="com.kh.pojo">

这个SQL映射语句中:

                namespace:一般设置为这个XML文件所在的package名字;

            如:本项目的这个Category.xml 就在com.kh.pojo包下面.

                                   在映射文件中配置很多SQL语句

id:标识映射文件中的SQL   //和js里面通过标签的id操作标签属性一样

将SQL语句封装到mappedStatement对象中,所以将id称为statement的id.这句话对照mybatis学习笔记(一)

parameterType:制定输入参数的类型.本项目中Category.class 就是创建了一个新的JAVA数据类型,相当于C语言中 定义 结构体一样.在Java中叫做JavaBean

               resultType:制定SQL输出结果所映射的JAVA对象类型,select制定resultType表示将单条记录影射成单条的Java对象,  学过JAVA泛型的人应该明白,在这里就不过多解释泛型了.

#{} 表示一个占位符号 '?'  //就是 JDBC中的  select * from category_ where id=?; 

#{id}:其中id表示接受输入的参数,参数名称就是id

如果输入参数是简单类型#{}中的参数名可以任意,可以是value或其他名称#{中国}都行.

(这个简单类型我解释一下: 就是JAVA的八大基础数据类型:byte short int long float double char boolean.再加上一个String类型的)只要是括号里面的这些数据类型,#{}中可以随意填,你填啥填啥啦啦辣~

执行TestSelect后控制台输出:


 
    
Category cg=sqlSession.selectOne("FindById", 1);

这句代码的意思就是:通过Category.xml中id="FindById"的这个标签(也就是<select>),执行它标签中的SQL语句,并把1赋给id.也就是说:  查找并输出id=1的那条记录. 

---------------------------------------------------------------------------------------------------------------------------------

2.插入操作:

运行之后,如图所示可以看到 通过Mybatis插入的数据里有新增加的Category

通过session.insert调用InsertCategory对应的SQL语句

Category cg = new Category();
cg.setName("rose");
session.insert("InsertCategory",cg);


InsertCategory对应的插入sql语句,#{name}会自动获取c对象的name属性值
<insert id="InsertCategory" parameterType="Category" >
insert into category_ ( name ) values (#{name})
</insert>

        同样先在Category.xml的<mapper>标签中,配置<insert>标签

<mapper namespace="com.kh.pojo">
        <select id="FindById" parameterType="int" resultType="Category"> 
            select * from   category_  where id=#{id}  
        </select>
        <!-- 添加
        	paramType:制定输入参数的类型是pojo
         -->
        <insert id="InsertCategory" parameterType="Category">
        insert into category_ (name) values(#{name})
        </insert>
</mapper>

执行语句

package com.kh.mybatis;

import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.kh.pojo.Category;

public class TestInsert {
	//插入用户信息
	public static void main(String[] args) throws IOException {
		//mybatis配置文件
		String resource="mybatis-config.xml";
    	InputStream inputStream=Resources.getResourceAsStream(resource);
    	//创建会话工厂
    	SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
    	//通过工厂得到SqlSessio
    	SqlSession sqlSession= sqlSessionFactory.openSession();
    	//插入用户
        Category cg=newCategory();
        cg.setName("rose");
        sqlSession.insert("insertCategory",cg);
    	//提交事务
    	sqlSession.commit();
    	System.out.println("插入成功");
    	sqlSession.close();
	}
}

数据据结果为下:成功插入了"rose";


---------------------------------------------------------------------------------------------------------------------------------

3.修改信息

     通过session.update进行修改

	Category cg=new Category();
    	cg.setId(6);//设置修改X号  将id=6的 name改为"你好"
    	cg.setName("你好");//将X号的name改为=? 
updateCategory对应的sql语句:
<update id="UpdateCategory" parameterType="Category" >
update category_ set id=#{id} where name=#{name}
</update>

编写测试代码:

package com.kh.mybatis;

import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.kh.pojo.Category;

public class TestUpdate {
	
	public static void main(String[] args) throws IOException {
		//mybatis配置文件
	String resource="mybatis-config.xml";
    	InputStream inputStream=Resources.getResourceAsStream(resource);
    	//创建会话工厂
    	SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
    	//通过工厂得到SqlSessio
    	SqlSession sqlSession= sqlSessionFactory.openSession();
    	//------------略略略----我是分割线--------------------------------------
      Category cg=new Category();
      cg.setId(6);//设置修改id=6的
      cg.setName("你好");//将id=6的name改为"你好"
      sqlSession.update("UpdateById",cg);
      sqlSession.commit();    	
    	System.out.println("更新成功----");
    	sqlSession.close();
	}
}

执行TestUpdate.class后      

---------------------------------------------------------------------------------------------------------------------------------

4.删除操作:

DeteleById对应的sql语句:

<delete id="DeleteById" parameterType="Category" >
    delete from category_ where id= #{id}   
</delete>
 
package com.kh.mybatis;

import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.kh.pojo.Category;

public class TestDetele {
	public static void main(String[] args) throws IOException {
	//mybatis配置文件
	String resource="mybatis-config.xml";
    	InputStream inputStream=Resources.getResourceAsStream(resource);
    	//创建会话工厂
    	SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
    	//通过工厂得到SqlSessio
    	SqlSession sqlSession= sqlSessionFactory.openSession();
    	//------------略略略----我是分割线--------------------------------------
    	sqlSession.detele("DeleteById",6);
         //提交事务
       sqlSession.commit();
      	System.out.println("删除成功");
    	sqlSession.close();
	}

}

执行TestDelete.class后:

------------------------------------------------------------------------------------------------------------------------------


以上就是使用Mybatis实现一些基本的增删改查操作.欢迎留言讨论.






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值