05 Mybatis的CRUD操作和Mybatis连接池

1.CRUD的含义

CRUD是指在做计算处理时的增加(Create)、读取(Retrieve)(重新得到数据)、更新(Update)和删除(Delete)几个单词的首字母简写。主要被用在描述软件系统中数据库或者持久层的基本操作功能。

2.URL的概念及含义

 

URL:Uniform Resource Locator 统一资源定位符。它是可以唯一标识一个资源的位置。
它的写法:
http://localhost:8080/mybatisserver/demo1Servlet
协议 主机    端口    URI

 

URI:Uniform Resource Identifier 统一资源标识符。它是在应用中可以唯一定位一个资源的。

 

3.Mybatis的CRUD操作

数据库表结构图:

数据库对应的实体类User.java

package domain;

import java.io.Serializable;
import java.util.Date;

/**
 * 数据库表对应的实体类
 */
public class User implements Serializable {
    //实体类的成员变量名称应该与数据库中的列名一致
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

IUserDao.java数据库表操作实现接口

package dao;

import domain.QueryConditon;
import domain.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.junit.Test;

import java.util.List;

/**
 *
 */
public interface IUserDao {
    /**
     * 查询所有
     * @return
     */
    //注解模式
    @Select("select *from user")
    List<User> findAll();

    /**
     * 保存用户
     * @param user
     */
    @Insert("insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})")
    void saveUser(User user);

    /**
     * 更新操作
     * @param user
     */
    @Update("update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id}")
    void updateUser(User user);


    /**
     * 删除操作
     * @param userId 用户id
     */
    @Delete("delete from user where id=#{userId}")
    void deleteUser(Integer userId);

    /**
     * 根据用户id查询
     * @param userId 用户id
     */
    @Select("select * from user where id=#{userId}")
    User queryById(Integer userId);

    /**
     * 根据用户名进行模糊查询
     * @param username 用户名
     * @return 查询结果
     */
    @Select("select *from user where username like #{username} ")
    List<User> queryByName(String username);

    /**
     * 获取用户的总记录数
     * @return
     */
    @Select("select count(id) from user")
    int queryTotalCount();

    /**
     * 根据查询条件对象(由实体类生成)进行查询
     * @param queryConditon 查询条件
     * @return
     */
    @Select("select *from user where username like #{user.username} and sex like #{user.sex}")
    List<User> queryByQueryConditionObject(QueryConditon queryConditon);
}

测试类

package test;

import dao.IUserDao;
import domain.QueryConditon;
import domain.User;
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 org.junit.Test;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class MybatisTest01 {

    private InputStream in;
    private SqlSession sqlSession;
    private IUserDao userDao;

    /**
     * 初始化MyBatis
     * @throws Exception
     */
    public void initMyBatis() throws Exception{
        //1.读取配置文件
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory
        SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder(); //创建SqlSessionFactory的构建者builder
        SqlSessionFactory factory=builder.build(in);  //利用构建者builder创建SqlSessionFactory
        //3.使用工厂生产SqlSession对象
        sqlSession = factory.openSession();
        //4.使用SqlSessions对象创建Dao接口的代理对象
        userDao = sqlSession.getMapper(IUserDao.class);
    }

    /**
     * 释放资源
     * @throws Exception
     */
    public void destroy() throws Exception{
        sqlSession.commit();//提交事务
        sqlSession.close();
        in.close();
    }

    /**
     * 查询所有
     */
    @Test
    public void testQueryAll() throws Exception{

        initMyBatis();
        //5.使用代理对象执行方法
        List<User> users = userDao.findAll();
        for (User user : users) {
            System.out.println(user);
        }
        destroy();
    }

    /**
     * 测试保存操作
     * @throws Exception
     */
    @Test
    public void testSave() throws Exception{
        User user=new User();
        user.setUsername("lucky");
        user.setAddress("天台");
        user.setBirthday(new Date());
        user.setSex("男");

        initMyBatis();
        //5.使用代理对象执行方法
        userDao.saveUser(user);

        destroy();
    }

    /**
     * 测试更新操作
     * @throws Exception
     */
    @Test
    public void testUpdate() throws Exception{
        User user=new User();
        user.setId(49);
        user.setUsername("lucky");
        user.setAddress("浙江天台");
        user.setBirthday(new Date());
        user.setSex("男");

        initMyBatis();
        //5.使用代理对象执行方法
        userDao.updateUser(user);

        destroy();
    }

    /**
     * 测试更新操作
     * @throws Exception
     */
    @Test
    public void testDelete() throws Exception{

        initMyBatis();
        //5.使用代理对象执行方法
        userDao.deleteUser(48);
        destroy();
    }

    /**
     * 测试查询一个的方法
     * @throws Exception
     */
    @Test
    public void testQueryOne()throws Exception{
        initMyBatis();
        //5.使用代理对象执行方法
        User user=userDao.queryById(49);
        System.out.println(user);
        destroy();
    }

    /**
     * 模糊查询
     * @throws Exception
     */
    @Test
    public void testQueryByName()throws Exception{
        initMyBatis();
        //5.使用代理对象执行方法
        List<User> users = userDao.queryByName("%ck%");
        for (User user : users) {
            System.out.println(user);
        }
        destroy();
    }

    /**
     * 查询总记录数
     * @throws Exception
     */
    @Test
    public void testQueryTotalCount()throws Exception{
        initMyBatis();
        //5.使用代理对象执行方法
        int totalCount = userDao.queryTotalCount();
        System.out.println(totalCount);
        destroy();
    }

    /**
     * 根据查询条件实体类对象进行查询
     * @throws Exception
     */
    @Test
    public void testQueryConditionObject()throws Exception{
        initMyBatis();
        QueryConditon queryConditon=new QueryConditon(); //创建查询条件实体类
        User user=new User();
        user.setUsername("%王%"); //查询条件1:名字包含王
        user.setSex("女");       //性别为女
        queryConditon.setUser(user); //将查询条件封装到查询条件实体类QueryConditon中
        //5.使用代理对象执行方法
        List<User> users = userDao.queryByQueryConditionObject(queryConditon);
        for (User user1 : users) {
            System.out.println(user1);
        }
        destroy();
    }

}

 4.Mybatis连接池

(1)连接池综述:
  我们在实际开发中都会使用连接池
  因为它可以减少我们获取连接所消耗的时间。


(2)mybatis中的连接池
mybatis连接池提供了3种方式的配置:
配置的位置:
  主配置文件SqlMapConfig.xml中的dataSource标签,type属性就是表示采用何种连接池方式。
  type属性的取值:
    POOLED    采用传统的javax.sql.DataSource规范中的连接池,mybatis中有针对规范的实现
    UNPOOLED    采用传统的获取连接的方式,虽然也实现Javax.sql.DataSource接口,但是并没有使用池的思想。
    JNDI                采用服务器提供的JNDI技术实现,来获取DataSource对象,不同的服务器所能拿到DataSource是不一样。
                 注意:如果不是web或者maven的war工程,是不能使用的。
            我们课程中使用的是tomcat服务器,采用连接池就是dbcp连接池。

转载于:https://www.cnblogs.com/luckyplj/p/11301850.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值