mybaits基本应用

本文详细介绍了如何在Mybatis中进行基本的数据库操作,包括创建学生表、配置环境、编写实体类、接口及工具类,以及XML映射文件的编写和实际操作演示。务必注意命名规则和配置一致性,是初学者理解Mybatis的好教程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Mybatis的一些基本增删改查操作

mybatis是一个基于Java的持久层框架,可以帮助我们方便快捷的对数据库进行操作,那么下面我们就以一张基本的学生表来展开说明。

操作步骤

  1. 创建一张学生表
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(40) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `email` varchar(40) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
  `age` int(11) NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Dynamic;
  1. 引入mybatis依赖
		<dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.6</version>
        </dependency>
  1. 配置mybatis
<?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>
    <typeAliases>
        <package name="vissan.domain"/>
    </typeAliases>
    
    <!-- environments : 运行环境,可以设置多个, default 表示默认的运行环境-->
    <environments default="development">
        <environment id="development">
        <!-- 当前事务交给JDBC进行管理--> 
            <transactionManager type="JDBC"/>
            <!-- 表示使用mybatis提供的连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/(此处为你的数据库名)?useUnicode=true&amp;characterEncoding=utf8&amp;autoReconnect=true&amp;rewriteBatchedStatements=TRUE"/>
                <property name="username" value="root"/>
                <property name="password" value="xxxx"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!--        对应要查询表的xml文件-->
        <mapper resource="vissan/mapper/StudentMapper.xml"/>
    </mappers>
</configuration>
  1. 编写对应的实体类和接口类以及工具类

Student实体类,此处我们使用lombok来简化开发

@Data
@ToString
public class Student {
    private Long id;
    private String name;
    private String email;
    private Integer age;
}

编写对应的mapper接口,定义基本的增删改查操作。

import java.util.List;

public interface StudentMapper {

    /**
     * 添加学生数据
     * @param student
     */
    void save(Student student);

    /**
     * 删除学生信息
     * @param iid
     */
    void delete(@Param("iid") int iid);

    /**
     * 更改学生信息
     * @param student
     */
    void update(Student student);

    /**
     * 查找学生信息
     * @return
     */
    List<Student> FindAll();
}

编写工具类来简化我们的代码

public class MyBatisUtil {

    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
      		 /**
             * 读取主配置文件,并将文件传入SqlSessionFactoryBuilder的build方法中,
             * 该方法会返回一个SqlSessionFactory对象
             */
            final InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	/**
     * 通过SqlSessionFactory来创建一个SqlSession对象并返回
     * @return SqlSession
     */
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }

}

  1. 编写StudentMapper.xml
    注意namespace要对应mapper层中对应的mapper接口
    id要与接口中定义的方法一致
<?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="vissan.mapper.StudentMapper">

    <insert id="save">
        insert into student (name, email, age) values(#{name}, #{email}, #{age})
    </insert>

    <update id="update">
        update student
    <set>
        <if test="name!=null"> name = #{name},</if>
        <if test="age!=null"> age = #{age},</if>
        <if test="email!=null"> email = #{email},</if>
    </set>
        where id = #{id}
    </update>

    <delete id="delete">
        delete from student where id = #{iid}
    </delete>

    <select id="FindAll" resultType="vissan.domain.Student">
        select * from student
    </select>

</mapper>
  1. 编写对应的实现类
public class StudentMapperimpl implements StudentMapper {

    @Override
    public void save(Student student) {
        final SqlSession sqlSession = MyBatisUtil.getSqlSession();
        final StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        studentMapper.save(student);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void delete(int iid) {
        final SqlSession sqlSession = MyBatisUtil.getSqlSession();
        final StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        studentMapper.delete(iid);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void update(Student student) {
        final SqlSession sqlSession = MyBatisUtil.getSqlSession();
        final StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        studentMapper.update(student);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public List<Student> FindAll() {
        final SqlSession sqlSession = MyBatisUtil.getSqlSession();
        final StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> list = studentMapper.FindAll();
        sqlSession.close();
        return list;
    }
}

7.注意事项
1、接口 和 xml文件,要同包同名称!!!
2、 Mapper.xml文件中的namespace与mapper接口的全限定名相同
3、Mapper接口方法名和Mapper.xml中定义的每条语句的id相同
4、Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql的parameterType的类型相同
5、文档永远是最好的学习工具,善用官方文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值