mybatis 入门教程

5 篇文章 0 订阅

今天,我捣鼓了下mybatis

-------------------------

mybatis环境搭建

-------------------------

我用的idea

首先需要创建maven项目

然后在pow.xml中加这些来下载依赖

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
    </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.29</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.12</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>
    </dependencies>

这是我的项目结构,没有的文件和文件夹先创建

后面会提供



mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTDConfig 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/ssm"/>
                <property name="username" value="root"/>
                <property name="password" value="zhangjun249"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--自动扫描所在包下的dao接口和xml映射文件-->
        <!--这里有坑 maven项目xml要放到resource文件夹中-->
        <package name="mapper"/>
    </mappers>

</configuration>

*注意看这里有坑

<mapper resource="mapper/>

-----------

这里是指定xml映射文件和dao接口的所在的包

如果创建的是maven项目,xml和dao接口不能放在一起

这里xml我放到了resource 文件夹下的mapper文件夹下了

然后dao接口放到java文件夹下的mapper文件夹下了

-----------------------------------------------------------------


我们先执行sql来创建表

create table t_user(
id int(50),
username varchar(50),
password varchar(50),
intruction varchar(255));

然后创建User类

package bean;  
  
public class User {  
    Integer id;  
    String username;  
    String password;  
    String intruction;  
  
    public User(Integer id, String username, String password, String intruction) {  
        this.id = id;  
        this.username = username;  
        this.password = password;  
        this.intruction = intruction;  
    }  
  
    public int getId() {  
        return id;  
    }  
  
    public void setId(int id) {  
        this.id = id;  
    }  
  
    public String getUsername() {  
        return username;  
    }  
  
    public void setUsername(String username) {  
        this.username = username;  
    }  
  
    public String getPassword() {  
        return password;  
    }  
  
    public void setPassword(String password) {  
        this.password = password;  
    }  
  
    public String getIntruction() {  
        return intruction;  
    }  
  
    public void setIntruction(String intruction) {  
        this.intruction = intruction;  
    }  
  
    @Override  
    public String toString() {  
        return "User{" +  
                "id=" + id +  
                ", username='" + username + '\'' +  
                ", password='" + password + '\'' +  
                ", intruction='" + intruction + '\'' +  
                '}';  
    }  
}  

我们可以通过SqlSessionFactoryBuilder和一个指定mybatic配置文件的路径来获得SqlSessionFactory

然后通过这个SqlSessionFactory来获得一个SqlSession

这里我就抽成一个类了

DBTool

package tool;

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 DBTool {
    private static SqlSessionFactory factory;

    static {
        try {
            String path = "mybatis-config.xml";
            InputStream is = Resources.getResourceAsStream(path);
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSession() throws IOException {
        // 每次都重新open会话
        return factory.openSession();
    }
}

我使用接口来指定要做的业务逻辑

package mapper;

import bean.User;

import java.util.List;

public interface UserMapper {
    /**
     * 添加用户
     */
    void insertUser(User user) throws Throwable;

    /**
     * 删除用户
     */
    void deleteUser(int id)throws Throwable;

    /**
     * 查询所有用户
     */
    List<User> getAllUser()throws Throwable;

    User getUser(int id)throws Throwable;
    /**
     * 修改用户
     */
    void modifyUser(User user)throws Throwable;
}

然后写sql映射文件

<?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="mapper.UserMapper">

    <insert id="insertUser" parameterType="bean.User">

insert into t_user (id,username,password,intruction) values(#{id},#{username},#{password},#{intruction})

</insert>

    <delete id="deleteUser" parameterType="int">
    delete from t_user where id=#{id}
</delete>
    <select id="getAllUser" resultType="bean.User">
        select * from t_user
        <where>
            <if test="id>5">
                And intruction='嘿嘿'
            </if>
        </where>
    </select>
    <select id="getUser" parameterType="int" resultType="bean.User">
        select * from t_user where id=#{id}
    </select>
    <update id="modifyUser" parameterType="bean.User">
        update t_user set username=#{username},password=#{password},intruction=#{intruction} where id=#{id}
    </update>
</mapper>

这里的<namespace="">如果要与接口对应起来的话,要写指定接口的类全名

这里有四个标签insert,select,delete,update分别对应数据库的插入,查询,删除,修改操作

-->然后每个标签又有id属性,用来标识映射语句,这个id与namaspace中指定的接口中的方法对应

-->resultType就是指定传递的参数的类型

-->id=#{id}这里是接收方法传递的叫做id的变量,然后将对应的值接收过来拼接成字符串(假如方法传递了5,那么这里就变成id=5).如果我们传递的是一个User对象,我们还可以直接使用传递的对象里面指定名字的变量名的值(见最后一个语句update)

-->where标签用于指定条件,通过条件生成动态sql,在where标签中加if标签,然后test就对应条件,当满足条件的时候,就将被if包围的字符串拼接到sql后面(mybatis做了处理,如果当前满足的条件是第一个,就会去掉and,避免尴尬)


这是测试代码

import bean.User;
import server.UserServer;

public class Content {
    public static void main(String[] args) {
        UserServer.insertUser(new User(8, "李青", "a10000236d69ff", "嘿嘿"));
        UserServer.modifyUser(new User(8, "张君", "传智学院", "哈"));
        System.out.println(UserServer.getAllUser().size());
        User user = (User) UserServer.getUserByID(8);
        System.out.println(user);
        UserServer.deleteUser(8);
    }

}

然后跑通了



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot、Vue-Element-Admin和MyBatis是一种常见的技术组合,用于构建现代化的Web应用程序。下面是一个简要的入门教程。 1. 首先,我们需要设置Spring Boot项目。可以使用Spring Initializr(https://start.spring.io/)来初始化一个基本的Spring Boot项目。在依赖项中添加Spring Web、Spring Data JPA和MyBatis等必要的依赖项。 2. 在Spring Boot项目中,我们需要创建实体类和数据库表的映射。使用JPA注解来定义实体类,并使用MyBatis注解来指定数据库表的映射。 3. 接下来,我们需要创建一个数据访问层(DAO)来处理与数据库的交互。使用MyBatis的注解或XML映射文件来定义SQL查询和操作。 4. 在Service层,编写业务逻辑代码来处理DAO返回的数据,并与其他组件进行交互。 5. 在Controller层,处理HTTP请求和响应,将数据传递给前端页面或接收前端发送的数据。使用Spring MVC注解来定义请求映射和参数解析。 6. 在前端方面,可以使用Vue-Element-Admin来构建用户界面。Vue是一种流行的JavaScript框架,用于构建灵活的单页面应用程序。Element-Admin是一个基于Vue的组件库,提供了丰富的UI组件和布局。 7. 在Vue-Element-Admin中,我们可以使用Vue Router来实现页面之间的导航和路由。使用axios来发送HTTP请求与后端进行数据交互。 8. 在Vue组件中,我们可以通过调用后端的API来获取数据并渲染到前端页面上。使用Element-Admin提供的布局和UI组件来美化页面。 通过上述步骤,我们可以实现一个基本的Spring Boot、Vue-Element-Admin和MyBatis入门教程。这个教程可以帮助初学者了解如何搭建和使用这个技术组合来构建现代化的Web应用程序。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值