springboot整合mybatis

该文详细介绍了如何在SpringBoot项目中集成Mybatis,包括添加mybatis-spring-boot-starter依赖,配置数据库连接信息,定义实体类和Mapper接口,编写MapperXML文件以实现增删查改操作。
摘要由CSDN通过智能技术生成

第一步:导入mybatis依赖

 <!--   mybatis-spring-boot-starter     -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

第二步:在application.properties中写入连接mysql的配置信息和mapper的配置(注:要先创建好对应的数据库和表哦!)

spring.datasource.username=root
spring.datasource.password=ww623025
spring.datasource.url= jdbc:mysql://127.0.0.1:3306/student?useUnicode=true&characterEncoding=UTF-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
//指定mybatis的实体类路径
mybatis.type-aliases-package=com.kuang.pojo
//指定xml映射文件路径
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

第三步:在新建pojo软件包,然后新建实体类

第四步:写入实体类字段要和数据库字段对应

public class User {
    private int id;
    private String userName;
    private String password;
}

 第五步:新建mapper接口并且写入要实现的方法

//这个注解表示了这是一个mybatis的 mapper类
@Mapper
@Repository
public interface UserMapper {
    List<User> queryUserList();

    User queryUserById(int id);
 
    int addUser(User user);

    int updateUser(User user);

    int deleteUser(int id);
}

第六步:在resources下创建mybatis文件,在mybatis下在新建mapper文件

然后创建对应的实体映射XML文件

 namespace="com.kuang.mapper.UserMapper" 这里就是这个xml的命名空间和对应的mapper接口进行了绑定

<!--绑定一个对应的dao/mapper接口-->  在文件中写就可以写增删查改了,

<?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.kuang.mapper.UserMapper">
    <select id="queryUserList" resultType="User">
        select * from user
    </select>

    <select id="queryUserById" parameterType="int"  resultType="User">
        select * from user where id=#{id}
    </select>

    <insert id="addUser" parameterType="User">
        insert into user(id,userName,password)
        value(#{id},#{userName},#{password})
    </insert>

    <update id="updateUser" parameterType="User">
        update user set userName=#{userName},password=#{password}
        where id=#{id}
    </update>

    <delete id="deleteUser" parameterType="int">
        delete from user where id=#{id}
    </delete>
</mapper>

基本上这样就配置完成了,实现一个基本的查询没问题就OK了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值