初见MyBatis之CRUD操作

      初见Mybatis之CRUD操作

       MyBatis是一个半自动化映射的ORM框架,可以极大的简化访问数据库的操作,又不失灵活性,本文通过一个实例来介绍如何MyBatis进行增删改查操作。Mybatis进行数据库的CRUD操作主要分为三个步骤:

      一丶CRUD操作基本流程

      1.配置Mapper配置文件:Mapper文件用来设计CRUD的sql语句内容,以及输入参数和返回参数,这是Mybatis灵活性的体现,可自己优化复杂的sql语句性能,以及配置存储过程等。

      2.配置MyBatis_config配置文件:这个配置文件是mybatis的主配置文件,用来配置和数据库的相关信息,在这个文件中需要引用Mapper配置文件。

      3.Dao层的代码中,调用Mybatis提供的API,完成数据的操作。利用MyBatis提供的API访问数据库一般是如下流程:

读取Mybatis配置文件->创建SqlSessionFactory->创建SqlSession对象->指向sql语句。

      二丶CRUD操作案例,通过一个对Customer表进行增删改查的案例,介绍Mybatis的CRUD操作。

                   

                 图1 数据库中customer表的内容

    1.customer对应表的实体对象设计:

  /**
 * customer对应POJO类
 * @authorSmartTu
 */
public classCustomer {
    publicint id;
    publicString name;
    publicString job;
    publicString telephone;
    publicint getId() {
       returnid;
    }
    publicvoid setId(int id) {
       this.id= id;
    }
    publicString getName() {
       returnname;
    }
    publicvoid setName(String name) {
       this.name= name;
    }
    publicString getJob() {
       returnjob;
    }
    publicvoid setJob(String job) {
       this.job= job;
    }
    publicString getTelePhone() {
       returntelephone;
    }
    publicvoid setTelePhone(String telePhone){
       this.telephone= telePhone;
    }
    @Override
    publicString toString() {
       return"Customer [id=" + id + ", name=" + name + ",job=" + job + ", telephone=" + telephone + "]";
    }
}

 2.Mybatis中Mapper映射文件配置,在本案例中这Mapper配置文件名是CustomerMapper,路径是com.bupt.customer

   <?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bupt.mapper.CustomerMapper">
    <!--直接执行sql,用来完成mybatis中动态建表语句-->
    <update id="createTable"parameterType="String">
       ${sql}
    </update>
    <!-- 插入操作-->
    <insert id="insertCustomer"parameterType="com.bupt.crud.Customer">
       insert intoCustomer(id,name,job,telephone) value(#{id},#{name},#{job},#{telephone});
    </insert>
    <!-- 更新操作-->
    <update id="updateCustomer"parameterType="com.bupt.crud.Customer">
       update customer setname=#{name},job=#{job},telephone=#{telephone} where id=#{id}
    </update>
    <!-- 删除操作-->
    <delete id="deleteByid" parameterType="int">
       delete from customer where id=#{id}
    </delete>
    <!-- 通过id精准查询操作-->
    <select id="queryByid" parameterType="int"resultType="com.bupt.crud.Customer">
       select *from customer where id=#{id}
    </select>
    <!-- 通过name模糊查询操作-->
    <select id="queryByName"parameterType="String" resultType="com.bupt.crud.Customer">
       select*from customer where name like concat('%',#{name},'%');
    </select>
</mapper>

3.Mybatis的主配置文件,从主配置文件中,可以发现对数据库连接的相关内容进行了配置,并且引用了了先前配置Mapper对象(MyBatis主配置文件,应引用所有的Mapper文件)

<?xml version="1.0"encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
       <environments default="mysql">
           <environment id="mysql">
              <transactionManager type="JDBC"/>
              <dataSource type="POOLED">
                  <property name="driver"value="com.mysql.jdbc.Driver"/>
                  <property name="url"value="jdbc:mysql://localhost:3306/mybatis"/>
                  <property name="username"value="root"/>
                  <property name="password"value="123456"/>
              </dataSource>
           </environment>
       </environments>
    <mappers>
           <!--引入映射配置文件-->
           <mapper resource="com/bupt/mapper/CustomerMapper.xml"/>
    </mappers>
    </configuration>

4,Dao代码操作数据库,CustomerDaoImpl类实现对了对数据库的增删改查操作。

public classCustomerDaoImpl implementsCustomerDao{
    /**
     * 1.这里必须要强调一下,SqlSessionFactory对象是非常消耗资源的一个类
     * 每一个数据库执需要new一个SqlSessionFactory对象即可
     * 如果一个数据库对应多个SqlSessionFactory对象,那么数据库资源会被耗尽
     * 2.在实际的开发中SqlSession对象应该设置为单例
     * 3.在这个程序中为了简单起见,没有利用单例示范,但是实际开发中运用单例是必须的
     * @throws IOException 获取SqlSession对象
     */
    publicSqlSession getSqlSession() throwsIOException{
       String configPath="mybatis_config.xml";
       InputStream inputStream = Resources.getResourceAsStream(configPath);
       SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
       SqlSession  sqlSession = sessionFactory.openSession();
       returnsqlSession;
    }
    /**
     * @param customer待插入对象的实体类
     */
    @Override
    publicvoid insertCustomer(Customer customer)throws IOException {
       // TODO Auto-generated method stub
       String configPath="mybatis_config.xml";
       InputStream inputStream = Resources.getResourceAsStream(configPath);
       SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
       SqlSession  sqlSession = sessionFactory.openSession();
       sqlSession.insert("com.bupt.mapper.CustomerMapper"+".insertCustomer",customer);
       sqlSession.commit();
       sqlSession.close();
    }
    /**
     * 通过customer的id更新customer对象
     * @param customer 新对象
     */
    @Override
    publicvoid update(Customer customer) throws IOException {
       // TODO Auto-generated method stub
       SqlSession sqlSession = getSqlSession();
       sqlSession.update("com.bupt.mapper.CustomerMapper"+".updateCustomer",customer);
       sqlSession.commit();
       sqlSession.close();
    }
    /**
     * 通过id删除指定对象
     * @param id 待删除对象id
     */
    @Override
    publicvoid deleteByid(int id) throws IOException {
       // TODO Auto-generated method stub
       SqlSession sqlSession = getSqlSession();
       sqlSession.update("com.bupt.mapper.CustomerMapper"+".deleteByid",id);
       sqlSession.commit();
       sqlSession.close();
    }
    /**
     * @param id 精确查找对象的id
     * @return Customer 通过id查询后的Customer对象
     */
    @Override
    publicCustomer queryByid(int id) throws IOException {
       // TODO Auto-generated method stub
       SqlSession sqlSession = getSqlSession();
       Customer customer =sqlSession.selectOne("com.bupt.mapper.CustomerMapper"+".queryByid",id);
       sqlSession.commit();
       sqlSession.close();
       returncustomer;
    }
    /**
     * 利用名字进行模糊查询
     * @param name 查询名字
     * @return 满足条件的customer对象集合
     */
    @Override
    publicList<Customer> queryByName(String name) throws IOException {
       // TODO Auto-generated method stub
       SqlSession sqlSession = getSqlSession();
       List<Customer> list =sqlSession.selectList("com.bupt.mapper.CustomerMapper"+".queryByName",name);
       sqlSession.commit();
       sqlSession.close();
       returnlist;
      
    }
}

5.测试代码,在测试过程中引入了Junit4单元测试框架

public classMainCustomer {
   
    @Test
    publicvoid insertTest(){
       Customer customer = new Customer();
       customer.id=3;
       customer.name="SmartTu";
       customer.job="student";
       customer.telephone="1314";
       CustomerDao customerDao = new CustomerDaoImpl();
       try{
           customerDao.insertCustomer(customer);
       } catch(IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
    }
    @Test
    publicvoid updateTest(){
       Customer customer = new Customer();
       customer.id=1;
       customer.name="SmartTuTu";
       customer.job="student";
       customer.telephone="1314";
       CustomerDao customerDao = new CustomerDaoImpl();
       try{
           customerDao.update(customer);
       } catch(IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
    }
    @Test
    publicvoid deleteTest(){
       intid= 1;
       CustomerDao customerDao = new CustomerDaoImpl();
       try{
           customerDao.deleteByid(id);;
       } catch(IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
    }
    @Test
    publicvoid queryByidTest(){
       intid= 1;
       CustomerDao customerDao = new CustomerDaoImpl();
       try{
           Customer customer =customerDao.queryByid(id);
           System.out.println(customer.toString());
       } catch(IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
    }
    @Test
    publicvoid queryByNameTest(){
       String name= "Tu";
       CustomerDao customerDao = new CustomerDaoImpl();
       try{
           List<Customer> list =customerDao.queryByName(name);
           for(int i =0;i<list.size();i++){
              System.out.println(list.get(i).toString());
           }
       } catch(IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
    }
}   




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值