MyBatis研究

入门级使用

参照MyBatis官网的简介与入门部分,尝试使用MyBatis,可创建新的Maven项目,引入以下依赖:

       
    
        org.mybatis
        mybatis
        3.5.8
    

    
        mysql
        mysql-connector-java
        5.1.49
    

其中,mysql-connector-java用于进行连接MySQL。

然后在项目resources目录下创建配置文件mybatis-config.xml:




    
    
    
    
        
            
            
            
            
                
                
                
                
            
        
    

    
    
        
        
    

其中涉及到一个变量配置文件config.properties以及一个生成的mapper xml文件:

config.properties(放入resources/下)配置内容如下:

username=root
password=123456
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/demo01?characterEncoding=utf8

mapper xml(放入resources/mapper/下)内容如下:




    

编写运行主类,具体代码如下:

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.example.mapper.BlogMapper;
import org.example.pojo.Blog;

import java.io.InputStream;


public class MybatisDemo01 {
    public static void main(String[] args) throws Exception {
        // 装载mybatis配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 创建sql会话工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        // Blog blog = session.selectOne("org.example.mapper.BlogMapper.selectBlog", 1);
        // 获取mapper
        BlogMapper blogMapper = session.getMapper(BlogMapper.class);
        Blog blog = blogMapper.selectBlog(1);
        System.out.println(blog);
    }
}

其中,涉及到的Java类包括:

  •  Pojo类:Blog.java,映射数据库Schema。类与DDL分别如下:
package org.example.pojo;


public class Blog {
    private Integer id;
    private String name;

    @Override
    public String toString() {
        return "Blog{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

DDL:

CREATE TABLE blog(id INT,name VARCHAR(20));

插入一条测试数据:

INSERT INTO blog(id, name)VALUES(1,'Jordan');
  • Mapper接口:BlogMapper.java
package org.example.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.example.pojo.Blog;


public interface BlogMapper {
// 注解或xml文件配置,两种方式均可
//    @Select("SELECT * FROM blog WHERE id=#{id}")
    Blog selectBlog(int id);
}

运行主类,结果:

MyBatis研究_第1张图片

你可能感兴趣的:(mybatis,java,开发语言)