一、使用Mybatis进行增删改查入门案例

MyBatis入门案例

环境准备

1、创建数据库和表

数据库名为mybatis,数据表名为student,复制下列代码运行即可。

CREATE DATABASE `mybatis`;
USE `mybatis`;
DROP TABLE IF EXISTS `student`;
 
CREATE TABLE `student` (
 `id` int(11) NOT NULL ,
 `name` varchar(255) DEFAULT NULL,
 `age` int(11) DEFAULT NULL,
 `email` varchar(255) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
 
insert  into `student`(`id`,`name`,`age`,`email`) values 
(1,'波哥',18,'2344565456@qq.com'),
(2,'詹姆斯·高斯林',60,'JamesGosling@163.com'),
(3,'不知火舞',200,'2345643567@sina.com'),
(4,'马可波罗',400,'2345643567@sohu.com');

2、创建项目

自行创建mybatis项目,正常创建java空项目即可。

3、导入jar包

提前准备好mysql数据库驱动和mybatis框架的jar包,在src同级目录中创建libs目录,并在其中添加jar包
在这里插入图片描述
添加红框中的jar包即可,其中junit为测试库,lombok为工具库。
然后需要右键libs目录,选择添加为库
在这里插入图片描述

4、添加mybatis的配置文件

resources目录下创建mybatis-config.xml 文件,主要是配置数据连接池和引入映射文件,内容如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <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/mybatis?useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com\cjy\dao\StudentDao.xml"/>
    </mappers>
</configuration>

右键resources目录,选择将目录标记为中的标记为资源根目录
在这里插入图片描述

入门案例

1、创建实体类

自行创建如下项目结构目录
在这里插入图片描述
然后在entity中创建实体类Student类,其中属性与数据库中的student表的列名一致。
在这里插入图片描述
其中@Data的作用是提供get/set方法,@NoArgsConstructor的作用是提供构造参数,不会用的朋友正常写get/set方法和构造参数就行。

2、创建dao层

创建dao层(持久层)的dao接口,定义操作数据库的方法(增删改查)

public interface StudentDao {
    // 查询学生表的所有数据
    List<Student> selectAllStudents();

    // 根据id查询学生数据
    Student selectStudentById(Integer id);

    // 添加学生数据到student表中
    void addStudent(Student student);

    //修改学生数据
    void reviseStudent(Student student);

    // 根据id删除学生数据
    void deleteStudentById(Integer id);
}

在同级目录创建与之对应的mapper文件——StudentDao.xml,SQL语句就是在这个mapper文件中写的。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cjy.dao.StudentDao">
    <select id="selectAllStudents" resultType="com.cjy.entity.Student">
        select * from student
    </select>

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

    <select id="selectStudentById" resultType="com.cjy.entity.Student">
        select * from student where id = #{id}
    </select>

    <update id="reviseStudent">
        update student set name=#{name},age=#{age},email=#{email} where id=#{id}
    </update>

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

一般来说,每个DAO接口都会有与之对应的mapper文件

编写测试类

创建MyBatisTest测试类

创建全局变量和工具方法
	private static SqlSessionFactory factory = null;
    public SqlSession tool() throws IOException {
        // 1.定义mybatis主配置文件的名称
        String config = "mybatis-config.xml";
        // 2.读(获)取mybatis主配置文件mybatis-config.xml的位置
        InputStream in = Resources.getResourceAsStream(config);
        // 3.创建 SqlSessionFactory 对象,目的是获取 SqlSession
        factory = new SqlSessionFactoryBuilder().build(in);
        //4.获取 SqlSession,SqlSession 能执行 sql 语句
        return factory.openSession();
    }

这个工具方法一般会在工具类中写,因为本次篇幅较短所以省略。

测试添加方法
@Test
    public void testInsert() throws IOException {
        SqlSession sqlSession = tool();
        // 5.创建保存数据的对象
        Student student = new Student();
        student.setId(6);
        student.setName("韩信");
        student.setAge(26);
        student.setEmail("23847387452@qq.com");
        // 6.执行 SqlSession 的 insert("参数1",参数2)方法
        // 参数1:要执行sql语句所在 sql映射文件的命名空间namesapce+ "."+sql标签中的id值
        int rows = sqlSession.insert("com.wz.dao.StudentDao.addStudent",student);
        // 7.输出结果   结果大于0  就证明添加成功
        System.out.println("增加记录的行数:"+rows);
        //8.提交事务
        sqlSession.commit();
        //9.关闭 SqlSession对象连接
        sqlSession.close();
    }
测试多个查询方法
@Test
    public  void testSelect() throws IOException {
        SqlSession sqlSession = tool();
        List<Student> studentList = sqlSession.selectList("com.wz.dao.StudentDao.selectAllStudents");
        //6.循环输出查询结果
        for(Student s:studentList){
            System.out.println("学生对象信息"+s);
        }
        //8.提交事务
        sqlSession.commit();
        //9.关闭 SqlSession对象连接
        sqlSession.close();
    }
测试单个查询方法
//查询指定id用户
    @Test
    public void getUserById() throws IOException {
        SqlSession sqlSession = tool();
        int id = 5;
        Student student = sqlSession.selectOne("com.wz.dao.StudentDao.selectStudentById",id);
        System.out.println(student);
        //8.提交事务
        sqlSession.commit();
        //9.关闭 SqlSession对象连接
        sqlSession.close();
    }
测试修改方法
//修改
    @Test
    public void updateUser() throws IOException {
        SqlSession sqlSession = tool();
        //创建student对象
        Student student = new Student();
        student.setId(5);
        student.setName("李白");
        student.setAge(23);
        student.setEmail("23847387452@qq.com");
        //执行sql
        int number = sqlSession.update("com.wz.dao.StudentDao.reviseStudent", student);
        //判断更新是否执行成功
        System.out.println(number);
        //8.提交事务
        sqlSession.commit();
        //9.关闭 SqlSession对象连接
        sqlSession.close();
    }
最后测试删除方法
//删除
    @Test
    public void deleteUser() throws IOException {
        SqlSession sqlSession = tool();
        int id = 5;
        int delete = sqlSession.delete("com.wz.dao.StudentDao.deleteStudentById", id);
        System.out.println(delete);
        //8.提交事务
        sqlSession.commit();
        //9.关闭 SqlSession对象连接
        sqlSession.close();
    }

总结

刚开始写这个入门案例可能会遇到很多问题,比如:
数据库8.0版本没有在driver属性中添加cj
数据库连接时表名错误,时区问题。
找不到resources中的mybatis配置文件等等。
其中都可以百度找到答案,我就是这样走过来的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值