Ibatis 配置

 

1.项目结构

Ibatis 配置

 

2.Gradle配置

 1 // 本gradle配置文件用于发布jar文件
 2 // 命令 $gradle build
 3 // 在 build/libs 目录下有jar文件
 4 
 5 // 版本号
 6 version = '1.0.0'
 7 
 8 // 插件
 9 apply plugin: 'java'
10 apply plugin: 'idea'
11 
12 // 仓库
13 repositories {
14     mavenLocal()
15     mavenRepo urls: ["http://maven.lujs.cn/nexus/content/groups/public/"]
16 //    maven {
17 //        url "http://maven.lujs.cn/nexus/content/groups/public/"
18 //    }
19 }
20 
21 // 编译java源码的jdk版本
22 sourceCompatibility = 1.6
23 
24 // 生成class文件的jdk版本
25 targetCompatibility = 1.6
26 
27 // 项目依赖
28 dependencies {
29 
30     // runtime 配置项中包含的依赖在运行时是必须的
31     // testCompile 配置项中包含的依赖,在编译测试代码时是必须的
32     // testRuntime 配置项中包含的依赖,在运行测试代码时是必须的
33     // archives 配置项中包含项目生成的文件(如jar文件)
34     // default 配置相中包含运行时必须的依赖
35     // providedCompile 编译时不会用到,运行时会用到
36     
37     testCompile (
38         [group:'junit', name:'junit', version:'4.11'],
39         [group:'org.unitils', name:'unitils-dbunit', version:'3.4.2']
40     )
41         
42     compile (
43         [group:'org.slf4j', name:'slf4j-log4j12', version:'1.7.13'],
44         [group:'log4j', name:'log4j', version:'1.2.17'],
45         [group:'com.ibatis', name:'ibatis', version:'2.3.4.726'],
46         [group:'com.oracle', name:'ojdbc', version:'6.0'],
47         [group:'org.springframework', name:'org.springframework.context', version:'3.2.5.RELEASE'],
48         [group:'joda-time', name:'joda-time', version:'1.6.2']
49     )
50     
51 }
52 
53 // jar包运行需要
54 jar{
55     // jar包依赖全打包
56     from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
57 
58     // 主main
59     manifest {
60         attributes 'Main-Class': 'com.h.Main'
61     }
62 }
63 
64 [compileJava, javadoc, compileTestJava]*.options*.encoding = 'UTF-8'

3.SqlMapConfig.XML

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
 3 <sqlMapConfig>
 4 
 5     <properties resource="jdbc.properties" />
 6 
 7     <settings cacheModelsEnabled="true"
 8               enhancementEnabled="true"
 9               errorTracingEnabled="true"
10               lazyLoadingEnabled="true"
11               useStatementNamespaces="true"/>
12 
13     <transactionManager type="JDBC">
14         <dataSource type="SIMPLE">
15             <property name="JDBC.Driver" value="${jdbc.driverClassName}" />
16             <property name="JDBC.ConnectionURL" value="${jdbc.url}" />
17             <property name="JDBC.Username" value="${jdbc.username}" />
18             <property name="JDBC.Password" value="${jdbc.password}" />
19         </dataSource>
20     </transactionManager>
21 
22     <sqlMap resource="table/fnddata/Example.xml" />
23 
24 </sqlMapConfig>

4.JDBC.properties

1 jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
2 jdbc.url=jdbc:oracle:thin:@192.168.0.1:1521:yh
3 jdbc.username=username
4 jdbc.password=password

5.Example.XML

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-2.dtd">
 3 
 4 <sqlMap namespace="Example">
 5 
 6     <sql id="allFields">
 7         id,created_at,created_by,updated_at,updated_by
 8     </sql>
 9 
10     <select id="getAll" resultClass="com.h.db.dto.ExampleDTO">
11         select <include refid="allFields"/>
12         from example_table
13     </select>
14 
15     <select id="getByCreatedBy" parameterClass="string" resultClass="com.h.db.dto.ExampleDTO">
16         select <include refid="allFields"/>
17         from example_table
18         where created_by = #created_by#
19     </select>
20 
21     <delete id="delByCreatedBy" parameterClass="com.h.db.dto.ExampleDTO">
22         delete from example_table where created_by = #created_by#
23     </delete>
24 
25     <insert id="insert" parameterClass="com.h.db.dto.ExampleDTO">
26         <selectKey resultClass="long" keyProperty="id">
27             select seq_example_table.nextval from dual
28         </selectKey>
29         insert into example_table (
30         <include refid="allFields"/>
31         ) values (
32         #id#, sysdate, 'hang535', sysdate, 'hang535')
33     </insert>
34 
35 </sqlMap>

6.IBatisSqlMapClient.java

Ibatis 配置Ibatis 配置
 1 import com.ibatis.common.resources.Resources;
 2 import com.ibatis.sqlmap.client.SqlMapClient;
 3 import com.ibatis.sqlmap.client.SqlMapClientBuilder;
 4 
 5 import java.io.IOException;
 6 import java.io.Reader;
 7 
 8 /**
 9  * Created by yuhang535 on 2015/12/25.
10  */
11 public class IBatisSqlMapClient {
12     public static SqlMapClient get(String configXML) throws IOException {
13         Reader reader = Resources.getResourceAsReader(configXML);
14         SqlMapClient sc =  SqlMapClientBuilder.buildSqlMapClient(reader);
15         reader.close();
16         return sc;
17     }
18 }
View Code

7.Connection

Ibatis 配置Ibatis 配置
public interface IDbConnection {
    Connection get();
    void close();
}

public class SimpleDbConnection implements IDbConnection {

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

    private String username;
    private String password;
    private String url;
    private String driver;
    private Connection conn = null;

    @Override
    public Connection get() {
        try {
            if(null != conn) {
                if(!conn.isClosed()){
                    return conn;
                }
            }
            conn = DriverManager.getConnection(url, username, password);

            if(!conn.isValid(10000))
            {
                conn.close();
                conn = null;
            }
            LOGGER.info(String.format("Succeed to connect to db %s", url));
        } catch (SQLException e) {
            LOGGER.error(String.format("Fail to connect to db %s", url), e);
            conn = null;
        }
        return conn;
    }

    @Override
    public void close() {
        if(null != conn){
            try {
                conn.close();
            } catch (SQLException e) {
            }
            LOGGER.info(String.format("Close db connection %s", url));
        }
    }

    /**
     *
     * @param username
     * @param password
     * @param address
     * @param driver oracle.jdbc.driver.OracleDriver or com.mysql.jdbc.Driver
     */
    public SimpleDbConnection(String username, String password, String address, String driver) {
        this.username = username;
        this.password = password;
        this.url = address;
        this.driver = driver;
        try {
            Class.forName(this.driver);
        } catch (ClassNotFoundException e) {
            LOGGER.error("JDBC driver class isn't found", e);
        }
    }
}
View Code

8.Batch

Ibatis 配置Ibatis 配置
  1 public interface Batch<T>{
  2     int doBatch(SqlMapClient sqlMapClient, String sqlId, List<T> list) throws SQLException;
  3 }
  4 
  5 public class BatchDelete<T> implements Batch<T> {
  6 
  7     private BatchDelete(){}
  8 
  9     @Override
 10     public int doBatch(SqlMapClient sqlMapClient, String sqlId, List<T> list) throws SQLException {
 11         if(null == sqlMapClient){
 12             return 0;
 13         }
 14         sqlMapClient.startBatch();
 15         for (T value : list) {
 16             sqlMapClient.delete(sqlId, value);
 17         }
 18         return sqlMapClient.executeBatch();
 19     }
 20 
 21     static class InstanceFactory{
 22         public static final BatchDelete instance = new BatchDelete();
 23     }
 24 }
 25 
 26 public class BatchInsert<T> implements Batch<T> {
 27 
 28     private BatchInsert(){}
 29 
 30     @Override
 31     public int doBatch(SqlMapClient sqlMapClient, String sqlId, List<T> list) throws SQLException {
 32         if(null == sqlMapClient){
 33             return 0;
 34         }
 35         sqlMapClient.startBatch();
 36         for (T value : list) {
 37             sqlMapClient.insert(sqlId, value);
 38         }
 39         return sqlMapClient.executeBatch();
 40     }
 41 
 42     static class InstanceFactory{
 43         public static final BatchInsert instance = new BatchInsert();
 44     }
 45 }
 46 
 47 public class BatchUpdate<T> implements Batch<T> {
 48 
 49     private BatchUpdate(){}
 50 
 51     @Override
 52     public int doBatch(SqlMapClient sqlMapClient, String sqlId, List<T> list) throws SQLException {
 53         if(null == sqlMapClient){
 54             return 0;
 55         }
 56         sqlMapClient.startBatch();
 57         for (T value : list) {
 58             sqlMapClient.update(sqlId, value);
 59         }
 60         return sqlMapClient.executeBatch();
 61     }
 62 
 63     static class InstanceFactory{
 64         public static final BatchUpdate instance = new BatchUpdate();
 65     }
 66 }
 67 
 68 public class DAO<T> {
 69 
 70     SqlMapClient sqlMapClient = null;
 71 
 72     public DAO(SqlMapClient sqlMapClient) {
 73         this.sqlMapClient = sqlMapClient;
 74     }
 75 
 76     private SqlMapClient getSqlMapClient(){
 77         return sqlMapClient;
 78     }
 79 
 80     public List<T> selectForList(String sqlId, Object obj) throws SQLException {
 81         return getSqlMapClient().queryForList(sqlId, obj);
 82     }
 83     public List<T> selectForList(String sqlId) throws SQLException {
 84         return getSqlMapClient().queryForList(sqlId);
 85     }
 86 
 87     public List<Map<String,Object>> selectForMap(String sqlId, Object obj) throws SQLException {
 88         return getSqlMapClient().queryForList(sqlId, obj);
 89     }
 90     public List<Map<String,Object>> selectForMap(String sqlId) throws SQLException {
 91         return getSqlMapClient().queryForList(sqlId);
 92     }
 93 
 94     public T selectForObj(String sqlId, Object obj) throws SQLException {
 95         return (T)getSqlMapClient().queryForObject(sqlId, obj);
 96     }
 97     public T selectForObj(String sqlId) throws SQLException {
 98         return (T)getSqlMapClient().queryForObject(sqlId);
 99     }
100 
101     public int insertBatch(String sqlId, List<T> obj) throws SQLException {
102         return executeBatch(sqlId, obj, BatchInsert.InstanceFactory.instance);
103     }
104 
105     public Object insertObj(String sqlId, Object obj) throws SQLException {
106         return getSqlMapClient().insert(sqlId, obj);
107     }
108 
109     public int deleteBatch(String sqlId, List<T> obj) throws SQLException {
110         return executeBatch(sqlId, obj, BatchDelete.InstanceFactory.instance);
111     }
112 
113     public Object deleteObj(String sqlId, Object obj) throws SQLException {
114         return getSqlMapClient().delete(sqlId, obj);
115     }
116 
117     public int updateBatch(String sqlId, List<T> obj) throws SQLException {
118         return executeBatch(sqlId, obj, BatchUpdate.InstanceFactory.instance);
119     }
120 
121     public Object updateObj(String sqlId, Object obj) throws SQLException {
122         return getSqlMapClient().update(sqlId, obj);
123     }
124 
125     private int executeBatch(String sqlId, List<T> obj, Batch<T> fun) throws SQLException {
126         int ret = 0;
127         List<T> newObj = new ArrayList<T>();
128         if (null != obj) {
129             for (int i = 0; i < obj.size(); ++i) {
130                 newObj.add(obj.get(i));
131                 if (newObj.size() % Constant.MAX_LINE_NUMBER == 0) {
132                     ret += fun.doBatch(getSqlMapClient(), sqlId, newObj);
133                     newObj.clear();
134                 }
135             }
136         }
137         if (newObj.size() > 0) {
138             ret += fun.doBatch(getSqlMapClient(), sqlId, newObj);
139         }
140         return ret;
141     }
142 }
View Code

9.DAO

Ibatis 配置Ibatis 配置
 1 public class ExampleDAO {
 2 
 3     DAO<ExampleDTO> dao = null;
 4     public ExampleDAO(SqlMapClient sqlMapClient) {
 5         dao = new DAO<ExampleDTO>(sqlMapClient);
 6     }
 7 
 8     public void insert(List<ExampleDTO> list) throws SQLException {
 9         dao.insertBatch("ExampleDAO.insert", list);
10     }
11 
12     public void delByCreatedBy(List<ExampleDTO> list) throws SQLException {
13         dao.deleteBatch("ExampleDAO.delByCreatedBy", list);
14     }
15 
16     public List<ExampleDTO> getAll() throws SQLException {
17         return dao.selectForList("ExampleDAO.getAll");
18     }
19 
20     public  List<ExampleDTO> getByCreatedBy(String prdCode) throws SQLException {
21         return dao.selectForList("ExampleDAO.getByCreatedBy", prdCode);
22     }
23 }
View Code

10.DTO

Ibatis 配置Ibatis 配置
public class Base {
    /* 主键 */
    private Long id;
    /* 创建时间 */
    private Date created_at;
    /* 创建人 */
    private String created_by;
    /* 修改时间 */
    private Date updated_at;
    /* 修改人 */
    private String updated_by;

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }

    public Date getCreatedAt() {
        return created_at;
    }
    public void setCreatedAt(Date created_at) {
        this.created_at = created_at;
    }

    public String getCreatedBy() {
        return created_by;
    }
    public void setCreatedBy(String created_by) {
        this.created_by = created_by;
    }

    public Date getUpdatedAt() {
        return updated_at;
    }
    public void setUpdatedAt(Date updated_at) {
        this.updated_at = updated_at;
    }

    public String getUpdatedBy() {
        return updated_by;
    }
    public void setUpdatedBy(String updated_by) {
        this.updated_by = updated_by;
    }
}

public class ExampleDTO extends Base {

}
View Code

11.Proc

Ibatis 配置Ibatis 配置
 1 public class ProcExample {
 2 
 3     private static List<ExampleDTO> forInsert(boolean isTday) {
 4         List<ExampleDTO> list = new ArrayList<ExampleDTO>();
 5         return list;
 6     }
 7 
 8     private static List<ExampleDTO> forDelete() {
 9         List<ExampleDTO> list = new ArrayList<ExampleDTO>();
10         return list;
11     }
12 
13     public static void insert(SqlMapClient sqlMap, boolean isTday) throws SQLException {
14         ExampleDAO dao = new ExampleDAO(sqlMap);
15         dao.insert(forInsert(isTday));
16     }
17 
18     public static void delete(SqlMapClient sqlMap) throws SQLException {
19         ExampleDAO dao = new ExampleDAO(sqlMap);
20         dao.delByCreatedBy(forDelete());
21     }
22 
23     public static void selectAll(SqlMapClient sqlMap) throws SQLException {
24         ExampleDAO dao = new ExampleDAO(sqlMap);
25         List<ExampleDTO> list = dao.getAll();
26     }
27 
28     public static void selectByPrdCode(SqlMapClient sqlMap, String productType) throws SQLException {
29         ExampleDAO dao = new ExampleDAO(sqlMap);
30         List<ExampleDTO> list = dao.getByCreatedBy(productType);
31     }
32 }
View Code

12.Main

Ibatis 配置Ibatis 配置
 1 public class Main {
 2     static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
 3 
 4     public static void main(String[] args) {
 5         LOGGER.info("Hello everybody!");
 6 
 7         SqlMapClient sqlMap = null;
 8         try {
 9             sqlMap = IBatisSqlMapClient.get("SqlMapConfig.xml");
10             System.out.println("Succeed to connect to DB!");
11         } catch (IOException e) {
12             e.printStackTrace();
13         }
14 
15         try {
16             ProcExample.selectAll(sqlMap);
17         } catch (SQLException e) {
18             e.printStackTrace();
19         }
20     }
21 }
View Code