ibatis+spring 集成

作为开源的Orm对象映射框架,ibatis是一个线程安全,学习容易,但是开发相对于hibernate来说的话,就要繁锁些,没有很好的工具支持ibatis所有的配置几乎是通过手写,这样增加了开发者的难度、、好啦,言归正转。下面编写实现。

一、引入spring,ibatis jar包.

二、编写log4j.properties日志文件

      log4j.rootLogger=DEBUG,stdout

      log4j.appender.stdout=org.apache.log4j.ConsoleAppender
      log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
      log4j.appender.stdout.layout.ConversionPattern=%c{1}% - %m%n

      log4j.logger.java.sql.PreparedStatement=DEBUG

三、建立Student.java类映象属性

package org.terry.ibatis.pojo;

public class Student {
 private Long id;

 private String name;

 private String subject;

 private Long score;

 public Long getId() {
  return id;
 }

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

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public Long getScore() {
  return score;
 }

 public void setScore(Long score) {
  this.score = score;
 }

 public String getSubject() {
  return subject;
 }

 public void setSubject(String subject) {
  this.subject = subject;
 }
}

四、编写 student.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 namespace="student">
 <typeAlias alias="student" type="org.terry.ibatis.pojo.Student"/>
 <resultMap class="student" id="studentResult">
  <result property="id" column="id" jdbcType="number" javaType="java.lang.Long"/>
  <result property="name" column="name"/>
  <result property="subject" column="subject"/>
  <result property="score" column="score"/>
 </resultMap>
 
 <select id="selectAll" resultMap="studentResult">
  select * from student
 </select>
 
 <select id="findbyId" parameterClass="java.lang.Long" resultClass="student">
  select * from student where id=#id#
 </select>
 <insert id="insert" parameterClass="student">
  insert into student(id,name,subject,score) values(#id#,#name#,#subject#,#score#)
 </insert>
 <update id="update" parameterClass="student">
  update student set name=#name#,subject=#subject#,score=#score# where id=#id#
 </update>
 <delete id="delete" parameterClass="java.lang.Long">
  delete from student where id=#id#
 </delete>
</sqlMap>

五、编写 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>
 <sqlMap resource="org/terry/ibatis/pojo/student.xml"/>
</sqlMapConfig>

六、编写 StudentDao.java(实现类)

package org.terry.ibatis.dao;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.orm.ibatis.SqlMapClientCallback;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.terry.ibatis.pojo.Student;

import com.ibatis.sqlmap.client.SqlMapExecutor;

public class StudentDao extends SqlMapClientDaoSupport implements Idao{

 public void delete(Long id) {
  this.getSqlMapClientTemplate().delete("delete", id);
 }

 public Object findbyId(Long id) {
  return this.getSqlMapClientTemplate().queryForObject("findbyId", id);
 }

 public List getAll() {
  return (List)this.getSqlMapClientTemplate().execute(new SqlMapClientCallback(){

   public Object doInSqlMapClient(SqlMapExecutor sqlMapper) throws SQLException {
    return sqlMapper.queryForList("selectAll");
   }
   
  });
 }

 public void save(Object o) {
  this.getSqlMapClientTemplate().insert("insert", o);
 }

 public void update(Object o) {
  this.getSqlMapClientTemplate().update("update", o);
 }
 
 public static void main(String[] args) throws IOException {
   Resource re=new ClassPathResource("Ibatis-Context.xml");
   XmlBeanFactory xml=new XmlBeanFactory(re);
   StudentDao student=(StudentDao)xml.getBean("studentDao");
   Student stu=new Student();
   stu.setId(Long.valueOf(16));
   stu.setName("terry");
   stu.setScore(Long.valueOf(99));
   stu.setSubject("数学");
   student.delete(Long.valueOf(16));
 }
}

七、配置 ApplicationContext.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "
http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
 <bean id="dataSource"
  class="org.apache.commons.dbcp.BasicDataSource">
  <property name="driverClassName">
   <value>oracle.jdbc.driver.OracleDriver</value>
  </property>
  <property name="url">
   <value>jdbc:oracle:thin:@localhost:1521:orcl</value>
  </property>
  <property name="username">
   <value>terry</value>
  </property>
  <property name="password">
   <value>terry</value>
  </property>
 </bean>
 
 <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
  <property name="configLocation" value="SqlMapConfig.xml"/>
  <property name="dataSource" ref="dataSource"></property>
 </bean>
 
 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource"></property>
 </bean>
  <!-- 配置事务拦截器 -->
   <bean id="transactionIterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
    <!-- 事务拦截器需要注入一个事务管理器 -->
    <property name="transactionManager" ref="transactionManager"></property>
    <property name="transactionAttributes">
     <props>
      <prop key="insert*">PROPAGATION_REQUIRED</prop>
      <prop key="find*,get*">PROPAGATION_REQUIRED,readOnly</prop>
      <prop key="*">PROPAGATION_REQUIRED</prop>
     </props>
    </property>
   </bean>
  
   <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
    <property name="beanNames">
     <list>
      <value>*Dao</value>
     </list>
    </property>
    <property name="interceptorNames">
     <list>
      <value>transactionIterceptor</value>
     </list>
    </property>
   </bean>
 <bean id="studentDao" class="org.terry.ibatis.dao.StudentDao">
  <property name="sqlMapClient" ref="sqlMapClient"></property>
 </bean>
</beans>

这样Ibatis 集成 Spring就实现啦

 

阅读更多

ibatis+spring集成问题如何解决:-(

01-14

小弟最近在做struts+ibatis+spring集成的时候都能成功,但是在做一个功能的时候遇到了点小麻烦,描述如下:rnrn在系统启动的时候我想调用ibatis的SqlMapClient对象去查询数据库,加载一些数据到内存中,而不是通过struts页面跳转,通过action触发并通过spring的注入得到SqlMapClient对象并操作数据的,我现在只是想通过一个普通的类DictionaryInit来加载一些数据,在这里用到的就只有ibatis+spring,但是我总是得不到SqlMapClient的实例,配置感觉没有什么不正确的地方,各代码如下:rnrn[color=#0000FF]DictionaryInit.java[/color]源代码:rnrn[code=Java]rnrnpackage org.dhf.bbw.init;rnrnimport java.sql.SQLException;rnimport java.util.List;rnrnimport org.apache.log4j.Logger;rnimport org.dhf.bbw.admin.dictionary.bean.Dictionary;rnimport org.springframework.context.ApplicationContext;rnimport org.springframework.context.support.ClassPathXmlApplicationContext;rnrnimport com.ibatis.sqlmap.client.SqlMapClient;rnrnpublic class DictionaryInit //extends SqlMapClientDaoSupport //想通过继承SqlMapClientDaoSupport来得到SqlMapClient对象,也没能成功,总是空指针异常rn rn /**rn * 获得Log4j日志处理类实例rn */rn private Logger logger = Logger.getLogger(DictionaryInit.class);rn rn /**rn * 单例模式rn */rn private static DictionaryInit dicInit = new DictionaryInit();rn rn private DictionaryInit()rn rn rn rn public static DictionaryInit getInstance()rn return dicInit;rn rn rn protected SqlMapClient sqlMapClient;// = getSqlMapClientTemplate().getSqlMapClient();rnrn public List getAllParentNodetionary() rn rn// ApplicationContext context = new ClassPathXmlApplicationContext("../applicationContext-dataSource.xml");rn// sqlMapClient = (SqlMapClient)context.getBean("sqlMapClient");rn rn List reslutList = null;rn try rn reslutList = sqlMapClient.queryForList("getAllParentNodetionary");rn catch (SQLException e) rn //打印错误日志rn logger.error("查询数据字典根节点出错:" + e.toString());rn rn return reslutList;rn rn rn public List getDictionaryByParentNode(int parentNode) rn List reslutList = null;rn try rn reslutList = sqlMapClient.queryForList("getDictionaryByParentNode", parentNode);rn catch (SQLException e) rn //打印错误日志rn logger.error("查询数据字典子节点出错:" + e.toString());rn rn return reslutList;rn rnrn public void setSqlMapClient(SqlMapClient sqlMapClient) rn this.sqlMapClient = sqlMapClient;rn rnrnrn[/code]rnrnrn[color=#0000FF]applicationContext-dataSource.xml[/color]配置如下:rnrn[code=XML]rnrnrnrnrn rn rn rn oracle.jdbc.driver.OracleDriverrn rn rn jdbc:oracle:thin:@127.0.0.1:1521:BBWrn rn rn bbwrn rn rn bbwrn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rnrnrn[/code]rnrnrn[color=#0000FF]applicationContext.xml[/color]配置代码:rnrn[code=XML]rnrn rn rn rn rn rnrn[/code]rnrnrn[color=#0000FF]sqlmap-config.xml[/color]配置如下:rnrn[code=XML]rnrnrnrnrn rnrnrn[/code]rnrn[color=#0000FF]Dictionary.xml[/color]配置如下:rnrn[code=XML]rnrnrnrnrnrn rn rn rn rn rn rn rn rn rn rn rn select * from BBW_Dictionary where parentNode is nullrn rn rn rn select * from BBW_Dictionary where recid = #value#rn rn rn rn select * from BBW_Dictionary where parentNode = #value#rn rn rnrnrn[/code]rnrnrn不知道是什么问题,总是得不到SqlMapClient对象,就只是少了struts的action的触发就不行了!跪拜...谢谢

iBatis+Spring配置问题?

03-30

为已存在的数据表增加两个字段,我在model.xml 增加了rnrnrnrnrnrnrnrnrn rn insert into WS_PEOPLE_BA (BA_CODE,BA_P_BEGINDATE,BA_P_ENDDATE)rn values #ba_code#,#ba_p_begindate#,#ba_p_enddate#)rn rnrnrn并且在相应添加记录的类中增加了get和set的方法,但在初始化时,应用还是出现如下错误:rnorg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlMapClient' defined in class path resource [spring_common.xml]: Initialization of bean failed; nested exception is com.ibatis.common.exception.NestedRuntimeException: Error occurred. rnCause: com.ibatis.common.xml.NodeletException: Error parsing XML. rnCause: com.ibatis.common.exception.NestedRuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. rnCause: com.ibatis.common.xml.NodeletException: Error parsing XML. rnCause: com.ibatis.common.exception.NestedRuntimeException: Error parsing XPath '/sqlMap/insert'. rnCause: com.ibatis.common.beans.ProbeException: There is no READABLE property named 'ba_p_begindate' in class 'com.bb.abroad.model.BaModel'rnCaused by: com.ibatis.common.beans.ProbeException: There is no READABLE property named 'ba_p_begindate' in class 'com.bb.abroad.model.BaModel'rnCaused by: com.ibatis.common.exception.NestedRuntimeException: Error parsing XPath '/sqlMap/insert'. rnCause: com.ibatis.common.beans.ProbeException: There is no READABLE property named 'ba_p_begindate' in class 'com.bb.abroad.model.BaModel'rnrnrn是不是配置文件写的有错误,或者还有其他的配置和类文件需要修改更新???请赐教!rn

ibatis+spring出问题了··请高手们帮忙

05-16

[color=#FF0000]显示错误:[/color]rnCaused by: com.ibatis.common.xml.NodeletException: Error parsing XML. Cause: org.xml.sax.SAXParseException: Attribute "property" is required and must be specified for element type "result".rnCaused by: org.xml.sax.SAXParseException: Attribute "property" is required and must be specified for element type "result".rn at com.ibatis.sqlmap.engine.builder.xml.SqlMapConfigParser.parse(SqlMapConfigParser.java:81)rn at com.ibatis.sqlmap.client.SqlMapClientBuilder.buildSqlMapClient(SqlMapClientBuilder.java:62)rn at org.springframework.orm.ibatis.SqlMapClientFactoryBean.afterPropertiesSet(SqlMapClientFactoryBean.java:258)rn at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1099)rn at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:400)rn at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:234)rn at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:144)rn at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:277)rn at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:321)rn at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:87)rn at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:72)rn at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:63)rn at com.dao.EmpDao.main(EmpDao.java:49)rn[color=#FF0000]spring.xml:[/color]rnrnrnrnrn rn rn oracle.jdbc.driver.OracleDriverrn rn rn jdbc:oracle:thin:@127.0.0.1:1521:orclrn rn rn systemrn rn rn orclrn rn rn rn rn com/share/sqlmapconfig.xmlrn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rnrn[color=#FF0000]sqlMapConfig.xml:[/color]rnrnrn rn rn rn

ibatis+spring 整合报错...捆饶我好多天了...求教育...

05-16

先粘点代码吧..免得大家说我配置有问题.rnSpring 配置...rn====================================rnrnrnrnrn rn rn rn rn rn rnrnrn rn rn rn SqlMapConfig.xmlrn rn rnrnrn rn rn rn rn rn rn rn rnrnrnrnrn==============rnibatis配置rnrnrnrnrnrn rnrn==================================================================rnrnUser实体类 映射 XML.rnrnrnrnrnrnrn rn rn rn rn rn rn rn select a.id , a.name from ibatis as a rn rnrn rn rn select a.id , a.name from ibatis as a where a.name=#value#rn rnrn rn rn select a.id , a.name from ibatis as a where a.id=#value#rn rnrn rn rn insert into ibatis as a (a.id,a.name) values (#id#,#name#)rn rnrn rn rn update ibatis as a set a.name=#name# where a.id=#id#rn rnrn rn rn delete from ibatis where id=#value#rn rnrnrnrnrn==================================rnUser实现类rnrnpackage com.ctgusec.dao;rnrnimport java.util.List;rnrnimport org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;rnrnimport com.ctgusec.zhupan.model.User;rnrnpublic class UserDaoImpl extends SqlMapClientDaoSupport implements IUserDao rnrn public void delete(String id) rn getSqlMapClientTemplate().delete("deleteUsers", id);rn rnrn public User getById(String id) rn return (User)getSqlMapClientTemplate().queryForObject("getUsersById",id);rn rnrn public User getByName(String name) rn rn return (User)getSqlMapClientTemplate().queryForObject("getUsersByName",name);rn rnrn public List getList() rn return getSqlMapClientTemplate().queryForList("getAllUsers",null);rn rnrn public void save(User ibatis) rn getSqlMapClientTemplate().insert("insertUsers",ibatis);rn rnrn public void update(User ibatis) rn getSqlMapClientTemplate().update("updateUsers", ibatis);rn rnrnrnrn==========================================rnrnrnmain方法 测试..rnpackage com.ctgusec.zhupan;rnrnimport java.io.FileNotFoundException;rnimport java.util.ArrayList;rnimport java.util.Iterator;rnimport java.util.List;rnrnimport org.springframework.context.ApplicationContext;rnimport org.springframework.context.support.ClassPathXmlApplicationContext;rnimport com.ctgusec.dao.UserDaoImpl;rnimport com.ctgusec.zhupan.model.User;rnrnpublic class Test rnrn public static void main(String[] args) throws FileNotFoundException rn ApplicationContext context = new ClassPathXmlApplicationContext(rn "applicationContext_ibatis.xml");rn UserDaoImpl testDAOImpl = (UserDaoImpl) context.getBean("userDaoImpl");rnrn // 获得全查询列表rn System.out.println("获得全查询列表");rn List result = new ArrayList();rn result = testDAOImpl.getList();rn for (Iterator iter = result.iterator(); iter.hasNext();) rn User element = (User) iter.next();rn System.out.println(element.getName());rn rnrn // 根据用户名获得用户对象rn System.out.println("根据用户名获得用户对象");rn User ibatis = testDAOImpl.getByName("1");rn System.out.println(ibatis.getName());rnrn // 根据id获得用户对象rn System.out.println("根据id获得用户对象");rn User ibatis1 = testDAOImpl.getById("1");rn System.out.println(ibatis.getName());rnrn // 新增用户对象rn System.out.println("-----------------");rn System.out.println("新增用户对象前");rn List result1 = new ArrayList();rn result1 = testDAOImpl.getList();rn for (Iterator iter = result1.iterator(); iter.hasNext();) rn User element = (User) iter.next();rn System.out.println(element.getName());rnrn rn testDAOImpl.save(new User("3", "3")); // 新增用户rn System.out.println("新增用户对象后");rn List result2 = new ArrayList();rn result2 = testDAOImpl.getList();rn for (Iterator iter = result2.iterator(); iter.hasNext();) rn User element = (User) iter.next();rn System.out.println(element.getName());rn rn System.out.println("-----------------");rnrn // 删除用户对象rn System.out.println("-----------------");rn System.out.println("删除用户对象前");rn List result3 = new ArrayList();rn result3 = testDAOImpl.getList();rn for (Iterator iter = result3.iterator(); iter.hasNext();) rn User element = (User) iter.next();rn System.out.println(element.getName());rnrn rn testDAOImpl.delete("3"); // 删除用户rn System.out.println("删除用户对象后");rn List result4 = new ArrayList();rn result4 = testDAOImpl.getList();rn for (Iterator iter = result4.iterator(); iter.hasNext();) rn User element = (User) iter.next();rn System.out.println(element.getName());rn rn System.out.println("-----------------");rnrn // 更新用户对象rn System.out.println("-----------------");rn System.out.println("更新用户对象前");rn List result5 = new ArrayList();rn result5 = testDAOImpl.getList();rn for (Iterator iter = result5.iterator(); iter.hasNext();) rn User element = (User) iter.next();rn System.out.println(element.getName());rn rnrn User ibatis3 = testDAOImpl.getById("1");rn ibatis3.setName("new1");rn testDAOImpl.update(ibatis3);// 更新用户对象rnrn System.out.println("更新用户对象后");rn List result6 = new ArrayList();rn result6 = testDAOImpl.getList();rn for (Iterator iter = result6.iterator(); iter.hasNext();) rn User element = (User) iter.next();rn System.out.println(element.getName());rn rn System.out.println("-----------------");rnrn rnrn==================================================================rnrnrn目前的状况是这么个状况...rn不知道为什么 在User.XML里 如果我配置了 返回类型 和传递类型参数...一运行就会报错...rn但是...不执行其他的SQL...只执行 DEL 方法...也就是没有任何传递和返回参数的 就可以正常运行...rn头疼我好几天了.....谁能帮个忙啊....rnrn==================================================================rnrn报错的信息我也沾一下吧...rnrn

没有更多推荐了,返回首页