Mybatis(一)—实现对数据库的增删改查操作

1.Mybatis简介

MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。 MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码。
Mybatis通过xml或注解的方式将要执行的各种statement(statement、preparedStatement、CallableStatement)配置起来,并通过java对象和statement中的sql进行映射生成最终执行的sql语句,最后由mybatis框架执行sql并将结果映射成java对象并返回。

2.环境搭建

需要导入的jar包
mybatis-3.2.7.jar
mysql-connector-java-5.1.7-bin.jar
需要的所有jar包:
这里写图片描述
创建数据库和表
在study数据库创建中students表,表结构如下:
这里写图片描述

添加Mybatis的配置文件sqlconfig.xml
文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <!-- 配置数据库连接信息 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/study" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>

</configuration>

注意study是数据库的名称,其他的参数比如数据库账户名,密码。
该文件创建在src目录下。

3.创建表对应的实体类

Student代码如下:

public class Student {
    private Integer id;
    private String name;
    private String sex;
    private Integer age;
    private String tel;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", sex=" + sex
                + ", age=" + age + ", tel=" + tel + "]";
    }
}

4.sql映射文件

该文件创建在src目录下。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- namespace:命名空间,做sql隔离 ,访问sql语句时,sql的id前面要带着命名空间-->
<mapper namespace="student">

    <!-- 
    id:sql语句唯一标识,不能重复。
    parameterType:属性指明查询时使用的参数类型
    resultType:属性指明查询返回的结果集类型。resultType="com.mq.pojo.Student"表示返回值是Student类型
    #{}占位符:起到占位作用,如果传入的是基本类型(string,long,double,int,boolean,float等),那么#{}中的变量名称可以随意写,一般和属性名相同。
    java.lang.Integer也可以直接写成int
     -->
    <select id="findStuById" parameterType="java.lang.Integer" resultType="com.mq.pojo.Student">
        select * from students where id=#{id}
    </select>

    <!-- 
    如果返回结果为集合,可以调用selectList方法,这个方法返回的结果就是一个集合,所以映射文件中应该配置成集合泛型的类型
    ${}拼接符:字符串原样拼接,如果传入的参数是基本类型(string,long,double,int,boolean,float等),那么${}中的变量名称必须是value
    注意:拼接符有sql注入的风险,所以慎重使用
     -->

    <select id="findStuByName" parameterType="java.lang.String" resultType="com.mq.pojo.Student">
        select * from students where name like '%${value}%'
    </select>

    <!-- 
    #{}:如果传入的是pojo类型,那么#{}中的变量名称必须是pojo中对应的属性,
    如果要返回数据库自增主键:可以使用select LAST_INSERT_ID()-->

    <insert id="insertStu" parameterType="com.mq.pojo.Student" >
        <!-- 执行 select LAST_INSERT_ID()数据库函数,返回自增的主键
        keyProperty:将返回的主键放入传入参数的Id中保存.
        order:当前函数相对于insert语句的执行顺序,在insert前执行是before,在insert后执行是AFTER
        resultType:id的类型,也就是keyproperties中属性的类型
        -->
        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
            select LAST_INSERT_ID()
        </selectKey>
        insert into students (name,sex,age,tel) values(#{name},#{sex},#{age},#{tel})
    </insert>

    <delete id="delStuById" parameterType="int">
        delete from students where id=#{id}
    </delete>

    <!--传入的是一个pojo类型,就是一个新的对象  -->
    <update id="updateStuById" parameterType="com.mq.pojo.Student">
        update students set name=#{name} where id=#{id}
    </update>

</mapper>

在sqlconfig.xml注册映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <!-- 配置数据库连接信息 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/study"/>
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>


     <mappers>
        <!-- 注册Student.xml文件,这两个文件在同一个目录下,都在src目录下-->
         <mapper resource="Student.xml"/>
     </mappers>

</configuration>

5.测试方法

public class StudentTest {
private SqlSessionFactory factory;

    //作用:在测试方法前执行这个方法
    @Before
    public void FirstDo() throws Exception{
        //加载配置文件
        String resource = "sqlconfig.xml";
        //通过流将核心配置文件读取进来
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //通过核心配置文件输入流来创建会话工厂
        factory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    /**
     * 根据id查询对象。
     */
    @Test
    public void findStuById(){//通过工厂创建会话
        SqlSession openSession = factory.openSession();
        //第一个参数:所调用的sql语句= namespace+.+sql的ID。
        //查询单个对象,使用selectOne方法即可
        Student student = openSession.selectOne("student.findStuById", 4);
        System.out.println(student);
        openSession.close();
    }

    /**
     * 通过name进行模糊查询,返回结果应该是一个list集合,所以使用SqlSession的selectList方法。
     */
    @Test
    public void findStuByName(){//通过工厂创建会话
        SqlSession openSession = factory.openSession();
        //如果返回结果为集合,调用selectList方法,这个方法返回的结果就是一个集合
        List<Student> list = openSession.selectList("student.findStuByName", "羽");
        System.out.println(list);
        openSession.close();
    }

    /**
     * 插入数据,先创建表对应的对象,设置属性,然后调用insert方法。
     */
    @Test
    public void insertStu(){//通过工厂创建会话
        SqlSession openSession = factory.openSession();
        Student student=new Student();
        student.setAge(25);
        student.setSex("女");
        student.setTel("58938939");
        student.setName("貂蝉");

        openSession.insert("student.insertStu", student);
        //提交事务(mybatis会自动开启事务,但是它不知道何时提交,所以需要手动提交事务)
        openSession.commit();
        System.out.println("id值" + student.getId());
    }

    /**
     * 通过id删除数据
     */
    @Test
    public void delStuById(){
        SqlSession openSession = factory.openSession();
        //如果返回结果为集合,调用selectList方法,这个方法返回的结果就是一个集合
        openSession.delete("student.delStuById", 5);
        //提交事务
        openSession.commit();
        openSession.close();
    }

    /**
     * 更新数据,需要新创建一个对象。
     * 如果where条件是id,那么这个对象就需要设置id属性。
     */
    @Test
    public void updateStuById(){
        SqlSession openSession = factory.openSession();
        //如果返回结果为集合,调用selectList方法,这个方法返回的结果就是一个集合
        Student student=new Student();
        student.setId(2);
        student.setName("刘备");
        openSession.delete("student.updateStuById",student);
        //提交事务
        openSession.commit();
        openSession.close();
    }

}
  • 7
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值