Spring+ibatis示例

来源:互联网 发布:thinking in java答案 编辑:程序博客网 时间:2024/06/05 07:38

在网上也找了一些列子,但写了之后发现都不如 上面的。总是有一些这样那样的错误!自己测试没问题就发出来了。方便以后看看。

首先是jar包。共七个不能少的。commons-dbcp-1.4.jar,commons-logging-1.0.4.jar,commons-pool-1.3.jar,ibatis-sqlmap-2.3.4.726.jar,mysql-connector-java-3.1.10-bin.jar,spring.jar,sqljdbc.jar。对了我的spring.jar版本是1.2.7的。在配置sqlMapConfig.xml的时候有点区别 下面会讲到。

首先是数据库:CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) CHARACTER SET gbk DEFAULT NULL,
  `sex` char(1) CHARACTER SET gbk DEFAULT NULL,
  PRIMARY KEY (`id`)
)

然后是实体类:

package com.zyy.entity;

import java.io.Serializable;

public class Student implements Serializable{
    

    private static final long serialVersionUID = 1L;
    
    
    /**id**/
    private Integer id;
    /**name**/
    private String name;
    /**sex**/
    private String sex;
    
    public void setId(Integer id) {
        this.id = id;
    }
    
    public Integer getId() {
        return this.id;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getName() {
        return this.name;
    }
    
    public void setSex(String sex) {
        this.sex = sex;
    }
    
    public String getSex() {
        return this.sex;
    }
}

然后是接口:

package com.zyy.dao;

import java.util.List;

import com.zyy.entity.Student;

public interface StudentDao {
    
    public Integer insertStudent(Student student);

    public void updateStudent(Student student);

    public Student loadStudent(Integer id);
}

然后是接口实现类:

package com.zyy.dao.impl;

import java.util.List;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.zyy.dao.StudentDao;
import com.zyy.entity.Student;

public class StudentDaoImpl extends SqlMapClientDaoSupport implements StudentDao {

    @Override
    public Integer insertStudent(Student student) {
        return (Integer)getSqlMapClientTemplate().insert("addStudent", student);
    }

    @Override
    public Student loadStudent(Integer id) {
        return (Student) getSqlMapClientTemplate().queryForObject("loadStudent", id);
    }

    @Override
    public void updateStudent(Student student) {
        getSqlMapClientTemplate().update("updateStudent", student);
    }

}

然后是数据库的链接配置jdbc.properties文件:

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8
username=root
password=admin

其次实体类的映射文件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">
    <resultMap id="studentResult" class="student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="sex" column="sex"/>
    </resultMap>

    <sql id="studentColumn">
          id,name,sex
    </sql>
 
    <sql id="studentWhere">
            <isNotEmpty prepend="and" property="id">
                <![CDATA[ id like concat('%',#id#,'%') ]]>
            </isNotEmpty>
            <isNotEmpty prepend="and" property="name">
                <![CDATA[ name like concat('%',#name#,'%') ]]>
            </isNotEmpty>
            <isNotEmpty prepend="and" property="sex">
                <![CDATA[ sex like concat('%',#sex#,'%') ]]>
            </isNotEmpty>
      </sql>
 
    <insert id="addStudent" parameterClass="student">
        insert into student (id
        <isNotNull prepend="," property="name">name</isNotNull>
        <isNotNull prepend="," property="sex">sex</isNotNull>
        ) values(#id#
        <isNotNull prepend="," property="name">#name#</isNotNull>
        <isNotNull prepend="," property="sex">#sex#</isNotNull>
        )
       <selectKey resultClass="java.lang.Integer" type="post" keyProperty="id" >
            select LAST_INSERT_ID();
        </selectKey>
    </insert>
    
    <update id="updateStudent" parameterClass="student">
        update student set id=#id#
        <isNotNull prepend="," property="name">name=#name#</isNotNull>
        <isNotNull prepend="," property="sex">sex=#sex#</isNotNull>
        where id=#id#
    </update>
    
    <select id="loadStudent" resultMap="studentResult" parameterClass="java.lang.Integer">
        select
            <include refid="studentColumn"/>
        from student
        where id=#value#
    </select>
    
</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>
<!--  给stuent类取个别名   -->
<typeAlias alias="student" type="com.zyy.entity.Student"/>
<!--  读取student的xml配置文件   -->
<sqlMap resource="Student.xml" />
</sqlMapConfig> 
在这里就要讲下spring.jar为什么要说明版本的问题。spring在3.0版本之后把jar包分成了很多份。比如spring-core.jar,spring-aop.jar等等。但是3.0版本之前他们还是一个整体。在spring1.x的版本sqlMapConfig.xml的头文件配置是上面的也就是:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" 
但是spring2.x的版本头文件配置就是如下的:

<?xml version="1.0" encoding="UTF-8"?>
   <beans
    
xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation
="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

如果你sqlMapConfig.xml文件的头配置和你的spring.jar版本配置不一致那么,就会报错org.xml.sax.SAXParseException: Document root element "beans", must match DOCTYPE root "null".的错误;我就被这个问题绊了一跤。


接下来是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>   
      <!-- 读取jdbc链接配置的值  -->
      <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>jdbc.properties</value>
            </list>
        </property>
    </bean>
      
      <!-- 数据库链接  -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">  
      <property name="driverClassName" value="${driverClassName}"/>  
      <property name="username" value="${username}"/>  
      <property name="password" value="${password}"/>  
      <property name="url" value="${url}"/>  
    </bean>  
      
    <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">  
      <!-- 此处应注入ibatis配置文件,而非sqlMap文件,否则会出现“there is no statement.....异常” -->  
      <property name="configLocation">  
         <value>sqlMapConfig.xml</value>  
      </property>  
      <property name="dataSource" ref="dataSource"/>
    </bean>  
 
  <!--dao注入设置  -->
      <bean id="studentDao" class="com.zyy.dao.impl.StudentDaoImpl">
          <property name="sqlMapClient" ref="sqlMapClient"/>
      </bean>
      
</beans>





上面的都做好了 就可以测试了:

package com.zyy.test;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.zyy.dao.StudentDao;
import com.zyy.entity.Student;

public class Text {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        StudentDao stuDao = (StudentDao) context.getBean("studentDao");
        
        //添加测试
//        Student stu = new Student();
//        stu.setName("张学友");
//        stu.setSex("男");
//        
//        Integer code = stuDao.insertStudent(stu);
//        
//        if (code > 0) {
//            System.out.println("添加成功!学生的ID:" + code);
//        }else {
//            System.out.println("添加失败!");
//        }
        
        //查询测试
//        Student student = stuDao.loadStudent(71);
//        if (student != null) {
//            System.out.println("学生的姓名:" + student.getName() + "\n" + "学生的性别:" + student.getSex());
//        }
        
        //修改测试
//        Student s = new Student();
//        s.setId(71);
//        s.setName("刘德华");
//        stuDao.updateStudent(s);
        
        
    }

}

把注释去掉就可以执行了!!!

0 0
原创粉丝点击