读书人

Ibatis简略应用

发布时间: 2012-09-01 09:33:03 作者: rapoo

Ibatis简单应用

?

jar包:

下载ibatis-2.3.0.677.jar

mysql驱动包

配置文件:

jdbc配置文件:db.properties

?

driver=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/test

username=root

password=root

数据库表:

?

DROP TABLE IF EXISTS `test`;

/*!40101 SET @saved_cs_client ? ? = @@character_set_client */;

/*!40101 SET character_set_client = utf8 */;

CREATE TABLE `test` (

??`id` int(11) NOT NULL AUTO_INCREMENT,

??`name` varchar(30) DEFAULT NULL,

??PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;

主配置:SqlMapConfig.xml (像hibernate中的hibernate.cfg.xml)

?

?

?类配置:Test.xml(像hibernate中的类名.hbm.xml不过那是对象映射,而这里配置的是所使用的sql

?

import java.io.IOException;import java.io.Reader;import java.util.List;import com.ibatis.common.resources.Resources;import com.ibatis.sqlmap.client.SqlMapClient;import com.ibatis.sqlmap.client.SqlMapClientBuilder;public class ITestDaoImpl implements TestDao {private static SqlMapClient sqlMapClient = null;static{try {Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);reader.close();} catch (IOException e) {e.printStackTrace();}}public void add(Test test) throws Exception {sqlMapClient.insert("add",test);}public void delete(int id) throws Exception {sqlMapClient.delete("delete",id);}@SuppressWarnings("unchecked")public List<Test> query() throws Exception {List<Test>list = sqlMapClient.queryForList("selectAll");return list;}@SuppressWarnings("unchecked")public List<Test> query(String name) throws Exception {List<Test>list = sqlMapClient.queryForList("fuzzyRetrieve",name);return list;}public Test query(int id) throws Exception {Test test = null;test = (Test)sqlMapClient.queryForObject("selectTestById",id);return test;}public void update(Test test) throws Exception {sqlMapClient.update("update", test);}

?以上即配置完成,直接使用mian函数测试,也可使用junit测试


?

ibatis缺点


sql需要自己写

参数数量只能一个


?

ibatis优点

减少代码

简单

?

sql语句与程序代码分离

简化项目中的分工

增强了移植性

读书人网 >编程

热点推荐