1. 创建数据库
CREATE TABLE `book` (
  `id` int(11) NOT NULL auto_increment,
  `bookname` varchar(32) NOT NULL COMMENT '书名',
  `author` varchar(32) default NULL COMMENT '作者',
  `publicationdate` datetime default NULL COMMENT '出版日期',
  `price` int(32) default NULL COMMENT '价格',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `book`(`id`,`bookname`,`author`,`publicationdate`,`price`) values (1,'西游记','吴承恩','1980-02-27 17:47:08',65),(2,'三国演义','罗贯中','1991-03-02 

15:09:37',59),(3,'水浒传','施耐庵','1984-05-02 17:29:33',61),(4,'红楼梦','曹雪芹','1994-06-06 21:33:18',88);

数据库视图

2. 创建maven工程并导入maven依赖jar包

一个基础的mybatis项目需要数据库连接驱动mybatis依赖包
我的数据库为mysql8,数据库驱动与mybatis版本都需要比较新的版本,根据自己的数据库版本使用相应的驱动就好

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
<!--mybatis依赖包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
3. 创建数据库对应实体类

com->test->pojo->Book.class

package com.test.pojo;


import java.util.Date;

public class Book {
    private int id;
    private String bookname;
    private String author;
    private Date publicationdate;
    private int price;

    public Book() {
    }

    public Book(int id, String bookname, String author, Date publicationdate, int price) {
        this.id = id;
        this.bookname = bookname;
        this.author = author;
        this.publicationdate = publicationdate;
        this.price = price;
    }

    @Override
    public String toString() {
        return "book{" +
                "id=" + id +
                ", bookname='" + bookname + '\'' +
                ", author='" + author + '\'' +
                ", publicationdate=" + publicationdate +
                ", price=" + price +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getBookname() {
        return bookname;
    }

    public void setBookname(String bookname) {
        this.bookname = bookname;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Date getPublicationdate() {
        return publicationdate;
    }

    public void setPublicationdate(Date publicationdate) {
        this.publicationdate = publicationdate;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }
}

4. 创建Mapper映射接口

com->test->mapper->BookMapper

package com.test.mapper;

import com.test.pojo.Book;

import java.util.List;

public interface BookMapper {
//    查询全部图书
    List<Book> findAllBook();
}

5. 编写数据库连接配置文件

resources->jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=Hongkong&characterEncoding=utf-8&autoReconnect=true
jdbc.username=root
jdbc.password=root
6. 编写mybatis配置文件

resources->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>

    <!--    通过properties标签加载外部properties文件-->
    <properties resource="jdbc.properties"></properties>
    <!--    自定义别名  -->
    <typeAliases>
        <typeAlias type="com.test.pojo.Book" alias="book"></typeAlias>
    </typeAliases>


    <!--    配置当前数据源的环境-->
    <environments default="development">
        <environment id="development">

            <!--            事务管理器           -->
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--    加载映射文件  -->
    <mappers>
        <mapper resource="com/test/mapper/BookMapper.xml"></mapper>
    </mappers>

</configuration>
7. 编写BookMapper的映射文件

resources->com->test->mapper->BookMapper.xml
需要注意的是!在resources中创建Directory要用 / 进行分隔!而不是 点!
在这里插入图片描述

<?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.test.mapper.BookMapper">
    <select id="findAllBook" resultType="book">
        select
        *
        from book
    </select>
</mapper>
8. 编写测试文件
package test;

import com.test.mapper.BookMapper;
import com.test.pojo.Book;
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 org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MybatisTest {
    //    加载mybatis配置文件(工厂图纸)
    InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
    //    获得工厂对象(sqlSessionFactory)
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    //    获得session会话对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //    获取mapper对象
    BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);

    public MybatisTest() throws IOException {
    }

    //    查
    @Test
    public void testSelect() {
        List<Book> allBook = bookMapper.findAllBook();
        for (Book book : allBook) {
            System.out.println(book);
        }
        sqlSession.close();
    }
}

9. 运行结果

输出成功
输出成功

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐