(9)Spring框架——MyBatis的学习

目录

 

一、概述

(一)项目准备工作

(二)项目结构描述

(三)具体作用概述

二、举例

(一)步骤

(二)实例


一、概述

(一)项目准备工作

0、思路:(个人理解,有可能有误因为是自学的。)

第一、mybatis是操作数据库,或者是跟持久层打交道的(我对着二个的理解就是实体类跟数据库的关系操作),需要配置一个mybatis的信息(1。需要配置数据库信息,如:mysql的登录密码账户等。2.sql语句的位置。),,因此创建了一个mybatis-config.xml文件。

第二、根据不同的实体类,创建不同的mapper.xml文件。这个文件里面是增删改查的sql语句。

第三、测试类里面可以通过(命名空间+id)来访问mapper.xm里面具体的sql语句。并交给sqlsession执行。

第四、测试类里面获取了mybatis-config.xml的核心配置,mapper位置,通过InputStream、SqlSessionFactory、SqlSession来构建成一个整体。直接传入参数,SqlSession执行mapper.xml里面的语句。

1、下载MyBatis。目标地址:https://github.com/mybatis/mybatis-3/releases?after=mybatis-3.4.4    (需要lib里面的所有JAR包、mybatis-3.4.2.jar(或者是其他的版本号))

2、数据库驱动jar包。如:mysql-connector-java-5.1.8.jar

(我的网盘链接:链接:https://pan.baidu.com/s/1ELGxGTauH40AUjgORvcrOQ 
提取码:75oo 
复制这段内容后打开百度网盘手机App,操作更方便哦)

(二)项目结构描述

(三)具体作用概述

1、log4j.properties主要是日志信息,效果如下:能把需要的日志信息打印在控制台上。(我是这么理解的)

2、mybatis-config.xml  这个配置文件主要作用:1、配置MyBatis的相关信息。2、数据库的连接属性(配置数据库如:Mysql,Oracle)。3、指定相关的mapper.xml文件的位置。

3、CustomerMapper.xml  这个配置文件主要作用是:1、写Sql语句。进行增删改查。

4、Customer  是一个实体类。

5、MybatisTest  是一个测试类。

二、举例

(一)步骤

1、导入相关jar包。

2、编写所有需要的配置文件。

3、创建实体类。

4、创建测试类。

(二)实例

1、导入相关jar包。

见项目准备,自行下载。(还有一个可以自行导入的JNUIT4。是一个单元测试的。通过工具可以直接导入。)

2、编写所有需要的配置文件。

(1)log4j.properties

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.stx=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
#这个日志文件的主要目的是为了在:控制台输出Sql语句。作用是:输出日志信息。这段代码在mybatis的操作手册里面可以查到。

(2)mybatis-config.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>
<!--    1.配置环境,默认的环境id为mysql-->
    <environments default="mysql">
<!--        1.2.配置id为mysql的数据库环境-->
        <environment id="mysql">
<!--            使用JDBC的事务管理器。-->
            <transactionManager type="JDBC"></transactionManager>
<!--            数据库连接池-->
            <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>
<!--    2.配置Mapper的位置。-->
    <mappers>
        <mapper resource="com/stx/mapper/CustomerMapper.xml"></mapper>
    </mappers>
</configuration>

(3)CustomerMapper.xml

<?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">
<!--!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd"
        1、这一段是MyBatis的约束配置。
        -->
<!--2、以下是映射信息-->
<!--
mapper是配置文件的根元素。
namespace 为这个<mapper>指定唯一命名空间。通常设置为:包名+sql映射文件。这个实在JAVA类里面的访问名称。通过这个名称来找到这个mapper的。
<select> 是mapper的子元素,用于执行查询操作。
          id 属性是唯一标识,
          parameterType 指定传入参数的类型。
          resultType 指定返回结果类型。
          #{} 表示一个占位符。相当于?,而#{id}表示该占位符待接收参数的名称为id。
-->
<mapper namespace="com.stx.mapper.CustomerMapper">
    <select id="findCustomerById" parameterType="Integer" resultType="com.stx.po.Customer">
        select * from t_customer where id=#{id}
    </select>
<!--  **************************************************************  -->
<!--    ${}:用来表示拼接SQL的字符串,即不加解释的原样输出。${value}表示要拼接的是简单类型参数。这样无法防止SQL注入。
            防止措施:使用MySQL中的concat()函数进行字符串拼接。
-->
<!--    <select id="findCustomerByName" parameterType="String" resultType="com.stx.po.Customer">-->
<!--        select * from t_customer where username like '%${value}'-->
<!--    </select>-->
    <select id="findCustomerByName" parameterType="String" resultType="com.stx.po.Customer">
        select * from t_customer where username like concat('%',#{value},'%')
    </select>
    <insert id="addCustomer" parameterType="com.stx.po.Customer">
        insert into t_customer(username,jobs,phone)
        values(#{username},#{jobs},#{phone})
    </insert>
    <select id="findAllCustomer" parameterType="String" resultType="com.stx.po.Customer">
        select * from t_customer
    </select>
    <update id="updateCustomer" parameterType="com.stx.po.Customer">
        update t_customer set username=#{username},jobs=#{jobs},phone=#{phone}
        where id=#{id}
    </update>
    <delete id="deleteCustomer" parameterType="Integer">
        delete from t_customer where id=#{id}
    </delete>
</mapper>

3、创建实体类。Customer 

package com.stx.po;

public class Customer {
    private Integer id;//主键
    private String username;//客户名称
    private String jobs;//职业
    private String phone;//电话

    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 String getJobs() {
        return jobs;
    }

    public void setJobs(String jobs) {
        this.jobs = jobs;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", jobs='" + jobs + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }
}

4、创建测试类。MybatisTest 

package com.stx.test;

import com.stx.po.Customer;
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.List;

//入门测试程序
public class MybatisTest {
    @Test
    public void findCustomerByIdTest() throws Exception{
//        1、读取配置文件,这个文件是MyBatis的核心配置文件。
        String resource = "mybatis-config.xml";
        InputStream inputStream =
                Resources.getResourceAsStream(resource);
//        2、根据配置文件构建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
//        3.通过SqlSessionFactory创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
//        4.SqlSession执行映射文件中定义的sql,并返回映射结果。
        Customer customer = sqlSession.selectOne("com.stx.mapper.CustomerMapper.findCustomerById",1);
//          打印输出结果。
        System.out.println(customer.toString());
//        关闭SqlSession
        sqlSession.close();
    }
    @Test
    public void findCustomerByNameTest() throws Exception{
        String resource ="mybatis-config.xml";
//        把配置文件作为输入流输入进去。
        InputStream inputStream = Resources.getResourceAsStream(resource);
//        根据配置文件构建sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//        通过sqlSessionFactory创建sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<Customer> customers = sqlSession.selectList("com.stx.mapper.CustomerMapper.findCustomerByName","j");
        for (Customer customer:customers){
            System.out.println(customer);
        }
        sqlSession.close();
    }
    @Test
    public void addCustomerTest() throws Exception{
//        1、读取配置文件
        String resource = "mybatis-config.xml";
//        2、根据配置文件构建SqlSessionFactory
        InputStream inputStream = Resources.getResourceAsStream(resource);
//        3、通过SqlSessionFactory创建SqlSession
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
//        4.SqlSession执行添加操作
//        4.1、创建Customer对象,并向对象中添加数据
        Customer customer = new Customer();
        customer.setUsername("Rose");
        customer.setJobs("Student");
        customer.setPhone("13996593272");
//        4.2、执行SqlSession的插入方法,返回的是sql语句的影响行数。
        int rows = sqlSession.insert("com.stx.mapper.CustomerMapper.addCustomer",customer);
//        4.3、通过返回结果判断插入操作是否执行成功。
        if (rows>0){
            System.out.println("您成功插入了"+rows+"条数据!");
        }else {
            System.out.println("执行插入操作失败了!!");
        }
//        4.4、提交事务。
        sqlSession.commit();
//        5、关闭SqlSession
        sqlSession.close();
    }
    @Test
    public void findAllCustomerTest() throws Exception{
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<Customer> customers =sqlSession.selectList("com.stx.mapper.CustomerMapper.findAllCustomer");
        for (Customer customer:customers){
            System.out.println(customer);
        }
        sqlSession.close();
    }
    @Test
    public void updateCustomerTest()throws Exception{
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Customer customer = new Customer();
        customer.setId(4);
        customer.setUsername("Rose");
        customer.setJobs("Programmer");
        customer.setPhone("13131111111");
        int rows=sqlSession.update("com.stx.mapper.CustomerMapper.updateCustomer",customer);
        if (rows>0){
            System.out.println("您成功修改了"+rows+"条数据!");
        }else {
            System.out.println("执行修改操作失败了!!!");
        }
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void deleteCustomerTest() throws Exception{
//        1、把配置文件赋值。
//        2、把配置文件加载成为字符字节流。读取配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
//        2、根据配置文件构建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//        3、通过SqlSessionFactory创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
//        4、SqlSession执行删除操作。
//        4.1 SqlSession执行删除方法,返回的是SQL语句影响的行数
        int rows = sqlSession.delete("com.stx.mapper.CustomerMapper.deleteCustomer",4);
//        4.2 通过返回结果判断是否删除成功。
        if (rows>0){
            System.out.println("成功删除了"+rows+"条数据!");
        }else {
            System.out.println("执行删除操作失败!!!");
        }
//        提交事务
        sqlSession.commit();
//        关闭sqlSession
        sqlSession.close();
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值