Mybatis访问Db2小例子

2022/2/9 19:13:09

本文主要是介绍Mybatis访问Db2小例子,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

环境

Db2

$ db2level
DB21085I  This instance or install (instance name, where applicable:
"db2inst1") uses "64" bits and DB2 code release "SQL11050" with level
identifier "0601010F".
Informational tokens are "DB2 v11.5.0.0", "s1906061700", "DYN1906061700AMD64",
and Fix Pack "0".
Product is installed at "/opt/ibm/db2/V11.5".

DB2 JCC driver

  • db2jcc_license_cu.jar
  • db2jcc4.jar
  • db2java.zip //没用
  • db2jcc.jar //不仅没用,而且会导致出错

注意,不能用 db2jcc.jar ,而要用 db2jcc4.jar 。当二者同时存在时,貌似就会用前者,从而报错: Method com/ibm/db2/jcc/am/hp.isClosed()Z is absstract

网上搜了一下,说是driver版本问题。

Anyway,只用 db2jcc4.jardb2jcc_license_cu.jar 就OK,同时不能有 db2jcc.jar

MyBatis

登录MyBatis官网(http://www.mybatis.org),下载最新的release。

注:该网址会自动重定向到 https://blog.mybatis.org 。

我下载的是mybatis-3.5.9.zip。

解压后,得到mybatis-3.5.9.jar,以及lib目录下一堆jar包。

Database

  • SAMPLE
$ db2 connect to sample

   Database Connection Information

 Database server        = DB2/LINUXX8664 11.5.0.0
 SQL authorization ID   = DB2INST1
 Local database alias   = SAMPLE

Table

  • T6
$ db2 describe table t6

                                Data type                     Column
Column name                     schema    Data type name      Length     Scale Nulls
------------------------------- --------- ------------------- ---------- ----- ------
C1                              SYSIBM    INTEGER                      4     0 Yes
C2                              SYSIBM    VARCHAR                      8     0 Yes

  2 record(s) selected.

编码

在Eclipse里新建一个Java project(本例中project name是 TestProject0209 ),在右键,属性,Java Build Path -> Libraries -> Add external JARs…,把Mybatis和jcc driver的jar包文件加进来,如下:

在这里插入图片描述

注:为了方便,我在project的根目录下创建了一个 lib 目录,并把3个jar文件都复制到这里了。

注:解压 mybatis-3.5.9.zip 后,在lib子目录下还有一堆jar文件,比如log4j-1.2.17.jar ,本例貌似用不上,所以不用加到project里了。

src 目录下创建3个package:

  • pojo
  • dao
  • service

pojo 下创建类 MyObject ,这是一个非常简单的POJO,对应DB里的一个table:

  • c1 成员变量对应table的 c1
  • c2 成员变量对应table的 c2
package pojo;

public class MyObject {
	private int c1;
	private String c2;

	public int getC1() {
		return c1;
	}

	public void setC1(int c1) {
		this.c1 = c1;
	}

	public String getC2() {
		return c2;
	}

	public void setC2(String c2) {
		this.c2 = c2;
	}
}

接下来我们来创建mapper,在 dao 下,创建 Test0209Mapper.javaTest0209Mapper.xml 文件。

  • Test0209Mapper.java
package dao;

import java.util.List;

import pojo.MyObject;

public interface Test0209Mapper {
	int insert(MyObject obj);
	
	List<MyObject> read();
}
  • Test0209Mapper.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="dao.Test0209Mapper">
	<insert id = "insert">
		insert into t6 (c1, c2) values (#{c1}, #{c2})
	</insert>
	
	<select id = "read" resultType="pojo.MyObject">
		select c1, c2 from t6
	</select>
</mapper>

在src目录下新建 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="db2">
    <environment id="db2">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.ibm.db2.jcc.DB2Driver"/>
        <!-- <property name="driver" value="com.mysql.jdbc.Driver"/> -->
        <property name="url" value="jdbc:db2://9.30.251.58:50000/sample"/>
        <property name="username" value="db2inst1"/>
        <property name="password" value="N1cetest"/>
      </dataSource>
    </environment>
  </environments>

    <mappers>
        <mapper class="dao.Test0209Mapper"/>
    </mappers>

</configuration>

注:

  1. 注释的driver属性,是MySQL的配置,若要改用MySQL,则这里需要相应改一下
  2. 所有mapper都定义在最下面的mapper处,本例中只使用了一个mapper dao.Test0209Mapper ,这是mapper类的全路径

最后,我们在 service 下创建 TestMybatis 类,来测试一下mapper:

package service;

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

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 pojo.MyObject;
import dao.Test0209Mapper;

public class TestMybatis {

	public static void main(String[] args) throws IOException {
		String resource = "mybatis-config.xml";
		
		InputStream inputStream = Resources.getResourceAsStream(resource);
		
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		
		SqlSession sqlSession = sqlSessionFactory.openSession(true);
		
		try {
			Test0209Mapper mapper = sqlSession.getMapper(Test0209Mapper.class);
			
			System.out.println("Test 1: query t6");
			List<MyObject> list = mapper.read();
			list.forEach(e -> System.out.println("c1: " + e.getC1() + ", c2: " + e.getC2()));

			System.out.println("Test 2: insert into t6");
			MyObject obj = new MyObject();
			obj.setC1(123);
			obj.setC2("abc");
			mapper.insert(obj);
			
			System.out.println("Test 3: query t6 again");
			list = mapper.read();
			list.forEach(e -> System.out.println("c1: " + e.getC1() + ", c2: " + e.getC2()));
		} finally {
			sqlSession.close();
		}
	}
}

运行程序,结果如下:

Test 1: query t6
c1: 111, c2: xxx
Test 2: insert into t6
Test 3: query t6 again
c1: 111, c2: xxx
c1: 123, c2: abc


这篇关于Mybatis访问Db2小例子的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程