mybatis 学习 一 lozz

创建maven项目

idea/eclipse

创建完成后编辑pom.xml文件

  • 设置源代码的编码格式

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
  • 设置编译源代码的jdk版本

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>
    </plugins>
</build>
  • 添加mybatis依赖
<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.5</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.28</version>
    </dependency>
    <!-- 其他依赖 -->
</dependencies>

跑起来

准备数据库
  • 创建一个数据库,编码设置为UTF-8。
CREATE DATABASE XXX DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
  •  创建表并插入数据
DROP TABLE IF EXISTS country;
CREATE TABLE country (
id int(32) NOT NULL,
country_name varchar(32) DEFAULT NULL,
country_code VARCHAR(10) DEFAULT NULL,
created datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

INSERT INTO country ( country_name, country_code, created )
VALUES ('中国','CN',sysdate()),('英国','GB',SYSDATE()),('俄罗斯','RU',SYSDATE()),('日本','JP',SYSDATE());
配置mybatis
创建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>
   <!-- 环境,可以配置多个,default:指定采用哪个环境 -->
   <environments default="test">
      <!-- id:唯一标识 -->
      <environment id="test">
         <!-- 事务管理器,JDBC类型的事务管理器 -->
         <transactionManager type="JDBC" />
         <!-- 数据源,池类型的数据源 -->
         <dataSource type="POOLED">
            <property name="driver" value="com.mysql.cj.jdbc.Driver" />
            <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis" />
            <property name="username" value="root" />
            <property name="password" value="123456" />
         </dataSource>
      </environment>
   </environments>
  </configuration>
创建实体类和Mapper.xml文件

根据数据库表country,创建实体类Country,代码如下

package org.course.apiauto.common.model;

import java.io.Serializable;

/**
 * @author the2n
 * @date 2020/06/15
 **/
public class Country implements Serializable {
    private static final long serialVersionUID = -2506443381060595715L;
    private String countryName;
    private String countryCode;
    private Long id;
    
    // get 和 set 方法
}

创建CountryMapper.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.course.apiauto.common.model.Country">
    <select id="listAll" resultType="org.course.apiauto.common.model.Country">
        select id, country_name,country_code from country
    </select>
</mapper>

构建sqlSessionFactory

// 指定全局配置文件
String resource = "mybatis-config.xml";
// 读取配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
// 构建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

完整代码

public class MyBatisUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyBatisUtil.class);

    private static SqlSessionFactory factory;

    static {
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            LOGGER.error("mybatis配置文件读取异常!" + e);
        }
    }

    /**
     * 创建session
     *
     * @return org.apache.ibatis.session.SqlSession
     */
    public static SqlSession openSession() {
        return factory.openSession();
    }
}

 测试代码:

/**
 * @author the2n
 * @date 2020/06/11
 **/
public class Demo {

    private SqlSession session;

    @Test
    public void init() {
        session = MyBatisUtil.openSession();
        try {
            List<BaseParameter> parameters = session.selectList("selectALL");
            for (BaseParameter parameter : parameters) {
                System.out.println(parameter);
            }
        }finally {
            session.close();
        }
    }

}

 

 

以上, 测试时使用的库非上文中创建的库,  可模仿 可超越~~~

posted @ 2020-06-15 16:10  Lozz  阅读(145)  评论(0)    收藏  举报