mybatis读数据库

举报
Nick Qiu 发表于 2020/10/23 12:23:15 2020/10/23
【摘要】 前言本文介绍如何在java中使用mybatis,本文使用maven项目。准备数据库create table `Blog`( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` CHAR(20) DEFAULT '' COMMENT '名字', PRIMARY KEY(`id`))COMMENT="博客";INSERT INTO Blog...

前言

本文介绍如何在java中使用mybatis,本文使用maven项目。

准备数据库

create table `Blog`(    `id` INT(11) NOT NULL AUTO_INCREMENT,    `name` CHAR(20) DEFAULT '' COMMENT '名字',
    PRIMARY KEY(`id`)
)COMMENT="博客";
INSERT INTO Blog (id,name) VALUES (101,'nick');
INSERT INTO Blog (name) VALUES ('nickqiu');

编码

  • 新建maven项目org.nick.mybatistest,加入依赖

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.nick</groupId>
    <artifactId>mybatis-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.4</version>
        </dependency>
    </dependencies></project>
  • mybatis 配置 mybatisdemo/src/main/resources/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>
    <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/test"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
                <!--<property name="url" value="${url}"/>-->
                <!--<property name="username" value="${username}"/>-->
                <!--<property name="password" value="${password}"/>-->
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="sqlmapping/BlogMapper.xml"/>
    </mappers></configuration>
  • 类配置文件mybatisdemo/src/main/resources/sqlmapping/BlogMapper.xml

<?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="org.nick.mybatistest.BlogMapper">
    <select id="selectBlog" resultType="org.nick.mybatistest.entity.Blog">
    select * from Blog where id = #{id}  </select></mapper>
  • 实体类mybatisdemo/src/main/java/org/nick/mybatistest/entity/Blog.java

package org.nick.mybatistest.entity;import lombok.Data;@Datapublic class Blog {    private int id;    private String name;
}
  • 数据库链接类mybatisdemo/src/main/java/org/nick/mybatistest/dao/DbConnect.java

package org.nick.mybatistest.dao;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 java.io.IOException;import java.io.InputStream;/**
 * 链接数据库
 */public class DbConnect {    private static SqlSessionFactory sqlSessionFactory = null;    private static String resource = "mybatis-config.xml";    private static synchronized void get(){        if(sqlSessionFactory == null){
            InputStream inputStream = null;            try {
                inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (
            IOException e) {
                e.printStackTrace();
            }
        }
    }    public static SqlSession  getSqlSection(){
        get();
        SqlSession session = sqlSessionFactory.openSession();        return  session;
    }

}
  • 测试类

package org.nick.mybatistest;import com.google.gson.Gson;import org.apache.ibatis.session.SqlSession;import org.nick.mybatistest.dao.DbConnect;import org.nick.mybatistest.entity.Blog;public class Application {    public static void main(String[] args) {

        SqlSession session = DbConnect.getSqlSection();        try {
            Blog blog = (Blog) session.selectOne("org.nick.mybatistest.BlogMapper.selectBlog", 101);
            System.out.println("blog:"+new Gson().toJson(blog));
        } finally {
            session.close();
        }
    }
}

执行效果



image.png

改造使用接口

  • 添加接口mapper类

package org.nick.mybatistest.dao;import org.apache.ibatis.annotations.Select;import org.nick.mybatistest.entity.Blog;public interface BlogMapper1 {    @Select("SELECT * FROM blog WHERE id = #{id}")    Blog selectBlog(int id);
}
  • 修改DB链接类的get方法,java代码中添加mapper

 package org.nick.mybatistest.dao;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.Configuration;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;import java.io.InputStream;/**
 * 链接数据库
 */public class DbConnect {    private static SqlSessionFactory sqlSessionFactory = null;    private static String resource = "mybatis-config.xml";    private static synchronized void get(){        if(sqlSessionFactory == null){
            InputStream inputStream = null;            try {
                inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
                Configuration configuration = sqlSessionFactory.getConfiguration();
                configuration.addMapper(BlogMapper1.class);
            } catch (
            IOException e) {
                e.printStackTrace();
            }
        }
    }    public static SqlSession  getSqlSection(){
        get();
        SqlSession session = sqlSessionFactory.openSession();        return  session;
    }

}
  • 新的测试类

package org.nick.mybatistest;import com.google.gson.Gson;import org.apache.ibatis.session.SqlSession;import org.nick.mybatistest.dao.BlogMapper1;import org.nick.mybatistest.dao.DbConnect;import org.nick.mybatistest.entity.Blog;public class Application1 {    public static void main(String[] args) {

        SqlSession session = DbConnect.getSqlSection();        try {
            BlogMapper1 mapper = session.getMapper(BlogMapper1.class);
            Blog blog = mapper.selectBlog(101);
            System.out.println("blog:"+new Gson().toJson(blog));
        } finally {
            session.close();
        }
    }
}


【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。