我的电脑操作系统版本为Win7旗舰版(ServicePack1),Oracle版本为Oracle11g
程序使用的jar包有:mybatis-3.2.2.jar、ojdbc14-10.2.0.2.0.jar
本例中使用的配置文件mybatis-config.xml,可以参见我的另一篇Blog《一个简单的MyBatis连接Oracle数据库的例子》(http://my.oschina.net/Tsybius2014/blog/626206)
现在Oracle数据库中建立一个新表RANK_LIST并插入一些数据,SQL如下:
CREATE TABLE RANK_LIST ( ID NUMBER(12,0) PRIMARY KEY, COMPETITION VARCHAR2(20) NOT NULL, RANK NUMBER(5, 0) NOT NULL, NAME VARCHAR(20) NOT NULL, INPUT_DATE NUMBER(10,0) DEFAULT TO_NUMBER(TO_CHAR(sysdate,'yyyymmdd')), INPUT_TIME NUMBER(10,0) DEFAULT TO_NUMBER(TO_CHAR(sysdate,'hh24miss')) ); INSERT INTO RANK_LIST (ID, COMPETITION, RANK, NAME) VALUES (1, 'COMP1', 1, 'TSYBIUS'); INSERT INTO RANK_LIST (ID, COMPETITION, RANK, NAME) VALUES (2, 'COMP1', 2, 'GALATEA'); INSERT INTO RANK_LIST (ID, COMPETITION, RANK, NAME) VALUES (3, 'COMP1', 3, 'GAIUS'); INSERT INTO RANK_LIST (ID, COMPETITION, RANK, NAME) VALUES (4, 'COMP1', 4, 'JULIA'); INSERT INTO RANK_LIST (ID, COMPETITION, RANK, NAME) VALUES (5, 'COMP2', 1, 'TSYBIUS'); INSERT INTO RANK_LIST (ID, COMPETITION, RANK, NAME) VALUES (6, 'COMP2', 2, 'GAIUS'); INSERT INTO RANK_LIST (ID, COMPETITION, RANK, NAME) VALUES (7, 'COMP2', 3, 'MARCUS'); INSERT INTO RANK_LIST (ID, COMPETITION, RANK, NAME) VALUES (8, 'COMP3', 1, 'QUINTUS'); INSERT INTO RANK_LIST (ID, COMPETITION, RANK, NAME) VALUES (9, 'COMP3', 2, 'MARCUS'); COMMIT; /
这个表中,ID为主键,COMPETITION为赛事,RANK为选手在这项赛事中取得的名次,NAME为选手的姓名。从PL/SQL中看到的RANK_LIST表内容如下:
现在要将获得了名次的选手按字母顺序正序取出,main函数调用代码如下:
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; /** * MyBatis使用测试 * @author Tsybius2014 * @date 2016年3月14日 * @time 下午10:55:12 * @remark * */ public class MyBatisTest { public static void main(String[] args) { try { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); try { RankListMapper mapper = session.getMapper(RankListMapper.class); List<String> productList = mapper.getWinnerList(); System.out.println(productList); } finally { session.close(); } } catch (Exception ex) { ex.printStackTrace(); } } }
RankListMapper.java代码如下:
import java.util.List; public interface RankListMapper { /** 获取在RANK_LIST表中榜上有名者的列表 */ List<String> getWinnerList(); }
RankListMapper.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="RankListMapper"> <select id="getWinnerList" resultType="java.lang.String" > SELECT NAME FROM RANK_LIST GROUP BY NAME ORDER BY NAME </select> </mapper>
上面的main函数,执行结果为:
[GAIUS, GALATEA, JULIA, MARCUS, QUINTUS, TSYBIUS]
END