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

news/2024/7/7 6:40:01

目录

 

一、概述

(一)项目准备工作

(二)项目结构描述

(三)具体作用概述

二、举例

(一)步骤

(二)实例


一、概述

(一)项目准备工作

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();
    }
}

 


http://www.niftyadmin.cn/n/4557276.html

相关文章

一个C++编程问题

而现在的方法是 按引用调用 (call by reference) 传递 即将实参复制给形参 如果去掉就编程 使用按值调用 (call by value) 来传递参数了 这样形参才能改变实参的值 这样实参的值不会被形参改变

HDU 2612 find a way 【双BFS】

<题目链接> 题目大意&#xff1a;两个人分别从地图中的Y 和 M出发&#xff0c;要共同在 处会面&#xff08;不止有一处&#xff09;&#xff0c;问这两个人所走距离和的最小值是多少。 解题分析&#xff1a; 就是对这两个点分别进行一次BFS&#xff0c;求出它们到每一个…

(10)Spring框架——MyBatis的学习之动态SQL

目录 一、描述 1、准备工作 2、总体思路 3、我出现的问题 二、步骤 1、根据项目结构建包&#xff0c;建类。 2、外部引入文件 三、实例 1、区别 一、描述 1、准备工作 &#xff08;1&#xff09;环境配置——相互作用 a.其中mybatis-config.xml&#xff08;配置数据…

(11)Spring框架——MyBatis的学习之动态SQL

目录 一、动态SQL的元素 二、实例 1、项目结构 2、建包建类 3、配置文件 一、动态SQL的元素 元素作用<if>是判断语句&#xff0c;当满足了条件就会执行标签里面的动态SQL <choose><when> <otherwise> <when>会进行多层判断&#xff0c;最后…

Go语言基础:method

我们在C语言中&#xff0c;struct中声明函数&#xff0c;而Go中则不能再struct中声明函数。而是采用另外一种形态存在&#xff0c;Go中叫method。 method的概念 method是附属在一个给定的类型上&#xff0c;语法和函数的声明语法几乎一样&#xff0c;只是再func后面增加了一个r…

输出1~50之间的质数。 用for循环语句编写

跳出循环 break; }if(ij)//当ij的时候就说明是质数了System.out.println(i);//输出质数就ok了} ||| 学习学习.. ";} } ||| 主要的方法体如下int i i); } } 答案补充 C 格式public class Test { public static void main(String[] args) { for(int k 50; --k > 2;) { i…

(12)Spring框架——MyBatis的学习之关联映射

目录 一、知识点 1、配置文件元素 二、概述 1、项目结构 2、描述 三、实例 1、mybatis-config.xml 2、db.properties 3、log4j.properties 4、mapper (1)、IdCardMapper.xml &#xff08;2&#xff09;、OrdersMapper.xml &#xff08;3&#xff09;、PersonMapper…

江苏省的二级C语言通过率如何

总是可以通过的 只要好好复习