Mybatis的简单使用


前言

对于Mybatis也是简单的学了一阵子了,现在来总结下Mybatis在项目中的简单使用(为了便于理解我这里只举一个简单的例子)


一、Mybatis是什么?

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录(网上复制)

如果真的感兴趣可以前往mybatis – MyBatis 3 | 简介

二、使用步骤

在这里项目我就不创建了,想了解如何创建maven请去idea创建maven中的servlet并运行_篆愁君的烦恼的博客-CSDN博客

1、在pom.xml中添加配置

在<dependencies></dependencies>之间添加

<dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.29</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.10</version>
    </dependency>

这两个,第一个是连接数据库的,一个是mybatis

2、删除web.xml中用不到的

初学者的话,基本上都用不到,功能不会有太大的差别

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <!-- Servlet Filters ================================================ -->

  <!--
    - Declare a filter for multipart MIME handling
    -->
 
</web-app>
        

保留头尾就可以了

3、在resources下面创建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>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>

这个是官网给我们的大致文件,根据自己的情况,将${driver}等,mapper映射改一下就可以用

 下面是我按我的弄好的

<?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.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="root1"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!--        包映射,不用指定到具体的文件-->
        <package name="com.izaijia.mapping"/>
        <!--        <mapper resource="org/mybatis/example/BlogMapper.xml"/>-->
    </mappers>

</configuration>

 4、创建实体类

这里根据自己创建的数据库表来创建,实体类属性最好和表名相同,不同的话,需要在后面创建的xml中修改

package com.izaijia.beans;

public class User {

    private int id;
    private String name;
    private String sex;

    public int getId() {
        return id;
    }

    public void setId(int 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;
    }

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

5、创建map映射

创建一个interface

建议把实体和映射放到两个包里

 idea插件商城里面有一个比较方便的Mybatis插件

 点击 文件=》设置=》插件

在安装好之后,会有一些特殊效果,这里还需要下一个步骤

6、创建映射的xml

这个在resource里面创建,直接创建一个与上面的interface同名包内

这里我的interface是在com.izaijia.mapping内

所以我在创建xml时,创建的是com/izaijia/mapping/usermapping.xml

创建成功后就是上面这个样子

下面这个是从整体看,那个MybatisDemo是一个运行类,到后面我会讲到

 

官网的文件内容是下面这个

<?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">
<mapper namespace="org.mybatis.example.BlogMapper">
  <select id="selectBlog" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>
将namespace改成映射的interface就好,id是方法名,returnType是返回值类型。
可以直接把它给的select删了

有两种方法

1、在usermapping.xml中生成

你可以直接在interface内写想要的方法

然后在方法后面点击alt+Enter

可以直接在xml内生成相应的代码,不过具体的还是要自己写

下面是自动生成的
<select id="getAllByIdUser" resultType="com.izaijia.beans.User"></select>

修改一下,加上查询语句

<select id="getAllByIdUser" resultType="com.izaijia.beans.User">
        select * from user ;
    </select>

下面是带有条件的

  User getByIdUser(int id);
<select id="getByIdUser" resultType="com.izaijia.beans.User">
        select * from user where id=#{id};
    </select>

 2、在interface中直接使用

这种的话,适合比较简单的sql语句,类似下面的

@Select("select * from user where id=#{id}")
    User selectById(int id);

通过注解解决,类似还有@Insert,@Update,@Delete等,当然,上一种方法和这个差不多,也有<insert><delete>等标签

另外,对于实体类属性和数据库表内属性名不同的情况,有下面这种方法解决

    <resultMap id="Type" type="com.izaijia.beans.User">
<!--        主键-->
        <id property="属性名" column="列名"></id>
<!--        其他-->
        <result property="属性名" column="列名"></result>
    </resultMap>

 但同时,之前的代码下面这个

<select id="selectById" resultType="com.izaijia.beans.User">
        查询语句
    </select>

 修改成下面这种形式

<select id="selectById" resultMap="Type">
        查询语句
    </select>

 7、创建运行的类

我们这里只是简单举例,就不写各种service,dao,imp的类了,就简单写一个运行类

1.获取SqlSessionFactory

根据 官网的提示,我们找到下面这个

String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

明显这个‘resource’就是我们的mybatis-config.xml文件,因为我们写到了resources里,且并没有放到包里(这个视你自己的情况),所以直接引用,改成下面这个

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

接下来 可以获取SqlSession

2、获取SqlSession对象

SqlSession sqlSession=sqlSessionFactory.openSession();

3、获取map映射

UserMapping mapper = sqlSession.getMapper(UserMapping.class);

 这个UserMapping就是咱创建的那个interface

创建好映射之后就可以直接用方法了

//    执行方法
    User user = mapper.selectById(1);
    System.out.println(user);

4、 关闭资源

sqlSession.close();

总结

Mybatis的简单应用并不难,但是深入却不简单,希望一起努力,mybatis的官网是mybatis – MyBatis 3 | 简介

想要进一步学习的可以去看看

另外,注意map映射xml的生成,是要与interface同包的,在resource生成,且是直接写成类似

com/izaijia/mapping/usermapping.xml

最后我把所有的代码再写一遍,如果有想要试试的,可以在这里复制一下

1、pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
-->
<!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <packaging>war</packaging>

  <name>ex</name>
  <groupId>com.izaijia</groupId>
  <artifactId>ex</artifactId>
  <version>1.0-SNAPSHOT</version>

  <build>
    <plugins>
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <version>6.1.7</version>
        <configuration>
          <connectors>
            <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
              <port>8888</port>
              <maxIdleTime>30000</maxIdleTime>
            </connector>
          </connectors>
          <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}</webAppSourceDirectory>
          <contextPath>/</contextPath>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <!--dependency>
      <groupId>com.izaijia</groupId>
      <artifactId>[the artifact id of the block to be mounted]</artifactId>
      <version>1.0-SNAPSHOT</version>
    </dependency-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.29</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.10</version>
    </dependency>
  </dependencies>

</project>

2、web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <!-- Servlet Filters ================================================ -->

  <!--
    - Declare a filter for multipart MIME handling
    -->

</web-app>
        

3、mybatis.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.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="root1"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!--        包映射,不用指定到具体的文件-->
        <package name="com.izaijia.mapping"/>
        <!--        <mapper resource="org/mybatis/example/BlogMapper.xml"/>-->
    </mappers>

</configuration>

4、User.java(实体类)

package com.izaijia.beans;

public class User {

    private int id;
    private String name;
    private String sex;

    public int getId() {
        return id;
    }

    public void setId(int 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;
    }

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

5、UserMapping.java

package com.izaijia.mapping;

import com.izaijia.beans.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserMapping {

    User getByIdUser(int id);

    List<User> selectAll();

    @Select("select * from user where id=#{id}")
    User selectById(int id);
}

 6、usermapping.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">
<mapper namespace="com.izaijia.mapping.UserMapping">
    <select id="selectAll" resultType="com.izaijia.beans.User">
    select * from user ;
  </select>
<!--    <resultMap id="Type" type="com.izaijia.beans.User">-->
<!--&lt;!&ndash;        主键&ndash;&gt;-->
<!--        <id property="属性名" column="列名"></id>-->
<!--&lt;!&ndash;        其他&ndash;&gt;-->
<!--        <result property="属性名" column="列名"></result>-->
<!--    </resultMap>-->
<!--    <select id="selectById" resultMap="Type">-->
<!--        查询语句-->
<!--    </select>-->
    <select id="getAllByIdUser" resultType="com.izaijia.beans.User">
        select * from user ;
    </select>
    <select id="getByIdUser" resultType="com.izaijia.beans.User">
        select * from user where id=#{id};
    </select>
</mapper>

 7、MysbatisDemo.java

import com.izaijia.beans.User;
import com.izaijia.mapping.UserMapping;
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 java.io.IOException;
import java.io.InputStream;

public class MybatisDemo {
//Driver
public static void main(String[] args) {

//1获取SqlSessionFactory
    String resource = "mybatis-config.xml";
    InputStream inputStream = null;
    try {
        inputStream = Resources.getResourceAsStream(resource);
    } catch (IOException e) {
        e.printStackTrace();
    }
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

//    2获取SqlSession对象
    SqlSession sqlSession=sqlSessionFactory.openSession();

//    3获取map映射
    UserMapping mapper = sqlSession.getMapper(UserMapping.class);
//    执行方法
    User user = mapper.selectById(1);
    System.out.println(user);

//    4关闭资源
    sqlSession.close();
}
}

8、数据库

CREATE DATABASE  IF NOT EXISTS `mybatis` /*!40100 DEFAULT CHARACTER SET utf8mb3 */ /*!80016 DEFAULT ENCRYPTION='N' */;
USE `mybatis`;
-- MySQL dump 10.13  Distrib 8.0.29, for Win64 (x86_64)
--
-- Host: 127.0.0.1    Database: mybatis
-- ------------------------------------------------------
-- Server version	8.0.29

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `user`
--

DROP TABLE IF EXISTS `user`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `user` (
  `id` int NOT NULL,
  `name` varchar(45) DEFAULT NULL,
  `sex` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `user`
--

LOCK TABLES `user` WRITE;
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
INSERT INTO `user` VALUES (1,'张三','男'),(2,'李四','女'),(3,'王五','男'),(4,'赵六','女'),(5,'钱七','男');
/*!40000 ALTER TABLE `user` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2022-07-12 19:19:43

最后这个是自动导出的,只看不注释的就行

 就到这里吧

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

篆愁君的烦恼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值