JAVA入门[6]-Mybatis简单示例

时间:2022-11-28 05:13:03

初次使用Mybatis,先手写一个hello world级别的例子,即根据id查询商品分类详情。

一、建表

create table Category (
Id INT not null,
Name varchar(80) null,
constraint pk_category primary key (Id)
);

插入测试数据

INSERT INTO category VALUES (1,'Fish');
INSERT INTO category VALUES (2,'Dogs');
INSERT INTO category VALUES (3,'Birds');

二、新建测试项目

新建Maven项目,最终的项目结构如下:

JAVA入门[6]-Mybatis简单示例

修改pom.xml,引入mybatis相关依赖。

<dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- Mysql数据库链接jar包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

 

三、建立pojo

建立Category对应的实体,这里为了方便测试重写了toString()方法。

public class Category implements Serializable {
    private int id;
    private String name;

    private static final long serialVersionUID = 1L;

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

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", id=").append(id);
        sb.append(", name=").append(name);
        sb.append("]");
        return sb.toString();
    }
}

四、定义数据访问接口

在src/main/cathy.mybatis/mapper包,新增CategoryMapper接口,这里只定义GetById方法。

public interface CategoryMapper {
    public Category GetById(int id);
}

五、配置mybatis xml文件

1.mybatis的配置都基于XML文件,我们放在resources/config/mybatis-config.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>
    <typeAliases>
        <typeAlias type="model.Category" alias="Category" />
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/store" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/CategoryMapper.xml" />
    </mappers>
</configuration>
  • typeAliases: 类型别名是为 Java 类型设置一个短的名字,用来减少类完全限定名的冗余。
  • dataSource:使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。
  • mappers:用来定义SQL映射语句

六、SqlSession工具类

构建SqlSession有多种方式,这里我们先从mybatis-config.xml配置文件构建SqlSessionFactory,然后从SqlSessionFactory获取SqlSession。

public static SqlSession getSqlSession() {
        SqlSession session = null;
        try {
            InputStream stream = Resources.getResourceAsStream(CONFIG_PATH);
            SqlSessionFactory factory = new SqlSessionFactoryBuilder() .build(stream);
            session = factory.openSession();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return session;
    }

 

七、调用:

public static void main(String[] args) {
        SqlSession sqlSession=MybatisUtils.getSqlSession();
        try{

            CategoryMapper categoryMapper=sqlSession.getMapper(CategoryMapper.class);
            Category category=categoryMapper.GetById(1);
            if(category==null){
                System.out.println("该分类不存在");
            }
            else{
                System.out.println(category.toString());
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        finally {
            MybatisUtils.closeSession(sqlSession);
        }
    }

 

运行结果:Category [Hash = 731395981, id=1, name=Fish]

 

源码地址:https://pan.baidu.com/s/1kUKXnMn