贴上项目结构
然后 SqlMapConfig.xml 配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <properties resource="jdbc.properties"/> <!-- maxRequests:同时执行SQL预计的最大线程数。 maxSessions:同一时间内活动的最大session数。 maxTransactions:同时进入SqlMapClient.startTransaction()的最大线程数。 cacheModelsEnabled:全局性地启用和禁用SqlMapClient的所有缓存model。 lazyLoadingEnabled:全局性地启用或禁用SqlMapClient的所有延迟加载。 enhancementEnabled:全局性地启用或禁用运行时字节码增强,以优化访问JavaBean属性的性能,同时优化延迟加载的性能。 useStatementNamespaces:如果启用本属性,必须使用全限定名来引用mapped statement。Mapped statement的全限定名由sql-map的名称和mapped-statement的名称合成。 --> <settings cacheModelsEnabled="true" lazyLoadingEnabled="true" maxRequests="32" maxSessions="10" maxTransactions="5" /> <transactionManager type="JDBC"> <dataSource type="SIMPLE"> <property name="JDBC.Driver" value="${jdbc.driverClassName}"/> <property name="JDBC.ConnectionURL" value="${jdbc.url}"/> <property name="JDBC.Username" value="${jdbc.userName}"/> <property name="JDBC.Password" value="${jdbc.password}"/> </dataSource> </transactionManager> <!-- <sqlMap>元素用于包括SQL Map映射文件和其他的SQL Map配置文件。每个SqlMapClient对象使用的所有SQL Map映射文件都要在此声明。映射文件作为stream resource从类路径或URL读入 --> <sqlMap resource="jnrj.xml"/> </sqlMapConfig>
jdbc.properties文件
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8 jdbc.userName=root jdbc.password=
log4j 文件
log4j.rootLogger=INFO, Console ###### Console appender definition ####### # All outputs currently set to be a ConsoleAppender. log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{3}] %m%n #log4j.appender.Console.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c] %m%n # 以下打印SQL语句 及所传参数 log4j.logger.com.ibatis=DEBUG log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG, A1
根据数据库创建对应实体文件,编写对应xml映射文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL MAP 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd"> <sqlMap> <!-- <typeAlias>元素为一个通常较长的、全限定类名指定一个较短的别名 --> <typeAlias alias="Jnrj" type="vo.Jnrj" /> <!-- 查询操作 --> <select id="getAll" resultClass="Jnrj"> select * from jnrj limit 0,10 </select> <select id="getAllMap" resultClass="hashmap"> select * from jnrj </select> <!-- parameterClass 所指定的JAVA类型可以简写 --> <select id="getJnrjVo" parameterClass="string" resultClass="Jnrj"> <![CDATA[ select * from jnrj where username = #username# ]]> </select> <select id="getJnrjWhere" parameterClass="hashmap" resultClass="Jnrj"> select * from jnrj <dynamic prepend="where"> <isNotEmpty prepend="and" property="username"> username like #username# </isNotEmpty> <isNotEmpty prepend="and" property="account"> account = #account# </isNotEmpty> </dynamic> order by $order$ desc </select> <sql id="insertSQL"> insert into jnrj(account,username,senddate,sendtime,books,contents,nums,path) values(#account#,#username#,#senddate#,#sendtime#,#books#,#contents#,#nums#,#path#) </sql> <insert id="insertJnrj" parameterClass="Jnrj"> <include refid="insertSQL" /> </insert> <!-- 使用 include 包含sql ,结果不能正常返回插入的主键 --> <insert id="insertJnrjKey" parameterClass="Jnrj"> insert into jnrj(account,username,senddate,sendtime,books,contents,nums,path) values(#account#,#username#,#senddate#,#sendtime#,#books#,#contents#,#nums#,#path#) <selectKey resultClass="int" keyProperty="id"> select LAST_INSERT_ID() as value </selectKey> </insert> </sqlMap>
测试代码:
package test; import java.io.IOException; import java.io.Reader; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import vo.Jnrj; import com.ibatis.common.resources.Resources; import com.ibatis.sqlmap.client.SqlMapClient; import com.ibatis.sqlmap.client.SqlMapClientBuilder; public class TestIbatis { static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); @SuppressWarnings("unchecked") public static void main(String[] args) throws IOException, SQLException { Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader); //测试返回List SQL语句分页 // List<Jnrj> list = sqlMap.queryForList("getAll"); // for (Jnrj j : list) { // print(j); // } //测试返回Map,自带分页 // List list = sqlMap.queryForList("getAllMap", 1, 10); // System.out.println(list.size()); //测试返回实体集合 // List<Jnrj> voJnrj = sqlMap.queryForList("getJnrjVo","稀范。"); // for(Jnrj j : voJnrj) // print(j); //测试插入 Jnrj jnrj = new Jnrj(); jnrj.setAccount("841359731"); jnrj.setUsername("阿斯兰"); jnrj.setSenddate(new Date()); jnrj.setSendtime("12 00 pm"); jnrj.setBooks("I LOVE 雪儿"); jnrj.setContents("LOVE U"); jnrj.setNums(10); jnrj.setPath(""); //插入无主键返回 // sqlMap.insert("insertJnrj", jnrj); // Object key = sqlMap.insert("insertJnrjKey", jnrj); // System.out.println(key != null ? key.toString() : ""); //测试动态SQL Map<String,Object> param = new HashMap<String, Object>(); param.put("username", "%阿斯兰%"); param.put("account", 841359731); param.put("order", "id"); List<Jnrj> jnrjList = sqlMap.queryForList("getJnrjWhere", param); for(Jnrj j : jnrjList) print(j); } private static void print(Jnrj j) { System.out.println(j.getId() + ":" + j.getAccount() + ":" + j.getUsername() + ":" + j.getBooks() + ":" + format.format(j.getSenddate()) + ":" + j.getSendtime()+"|"+j.getContents()); } }
include 标签可以包含 SQL 片段
一般情况下没问题,但是像上面插入一个返回主键一个不返回主键,将插入语句定义为 SQL 片段,在ID为 insertJnrjKey 的语句中用 include 语句引用
<insert id="insertJnrjKey" parameterClass="Jnrj"> <include refid="insertSQL"/> <selectKey resultClass="int" keyProperty="id"> select LAST_INSERT_ID() as value </selectKey> </insert>
根据打印的日志信息
select LAST_INSERT_ID() as value
会比插入语句先执行,返回主键key一直是 0。
映射文件中 # 和 $, #符号会进行预处理编译成了 问号,$ 类似直接拼接字符串
代码地址:
https://git.oschina.net/asilan/ibatis_demo.git