1、简介
与Hibernate相比,ibatis属于一种半自动的ORM框架,主要解决了java对象与SQL入参及结果集的映射关系。简单易学、容易上手;但是安全性较差,对于金融等对安全要求较高的系统来说,不推荐使用。
2、代码
首先看一下简单应用
project的结构
ibatis.xml 记录了JDBC连接数据库所需的信息
<?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> <transactionManager type = "JDBC" > <dataSource type = "SIMPLE" > <property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/> <property name="JDBC.ConnectionURL" value="jdbc:mysql://192.168.61.28/mytest"/> <property name="JDBC.Username" value="encysys48"/> <property name="JDBC.Password" value="encysys48"/> </dataSource> </transactionManager> <sqlMap resource = "com/jiexun/xml/user.xml" /> </sqlMapConfig>
ibatis.xml
user.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 alias = "user" type = "com.jiexun.User" /> <select id="getUser" parameterClass = "int" resultClass="user"> select * from user where user.id = #id# </select> <!-- 对象传参 user的属性中有id name 成员变量 --> <insert id="addUser" parameterClass="user"> insert into user values(#id#,#name#) </insert> <!-- Map传参 --> <insert id="addUser2" parameterClass="java.util.HashMap"> insert into user values(#id#,#name#) </insert> </sqlMap>
user.xml
package com.jiexun; public class User { public int id; public String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
com.jiexun.User
import java.io.Reader; import java.util.HashMap; import java.util.List; import com.ibatis.common.resources.Resources; import com.ibatis.sqlmap.client.SqlMapClient; import com.ibatis.sqlmap.client.SqlMapClientBuilder; import com.jiexun.User; public class testIbatis { /** * @param args */ public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub int id = 1001; User newUser = new User(); newUser.setId(1001); newUser.setName("LS"); String config = "com/jiexun/xml/ibatis.xml"; Reader reader = Resources.getResourceAsReader(config); SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader); //对象传参 插入 Object obj = sqlMap.insert("addUser",newUser); System.out.println("插入新用户返回值:" + obj); //Map传参 插入 HashMap paraMap = new HashMap<String, Object>(); paraMap.put("id", "1002"); paraMap.put("name", "WWN"); Object obj2 =sqlMap.insert("addUser2",paraMap); //查询 List<User> list = sqlMap.queryForList("getUser",id); System.out.println("执行select完毕"); for (User user : list) { System.out.println(user.id + ": " + user.name); } } }
testIbatis
数据库表结构:
CREATE TABLE `user` ( `id` int(10) DEFAULT NULL, `name` varchar(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8
创建表语句(MySQL)
时间: 2024-11-29 05:45:49