iBatis入门实例

iBatis开发环境配置如图:

实体类:Student.java

package com.sbw.entity;

public class Student {

    private int id;
    private String name;
    private float score;

    public int getId() %7@
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public float getScore() {
        return score;
    }
    public void setScore(float score) {
        this.score = score;
    }


}

在MySQL建立相应的数据库表:

mysql> create table student(
    -> id int auto_crement primary key,     -> name varchar(20) not null,     -> score float(5,2) not null     -> );

数据库相关配置资源文件:db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
user=root
password=root

iBatis 总配置文件: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="db.properties"/> <settings  cacheModelsEnabled="true" <!--是否启用缓存机制-- > enhancementEnabled="true" <!-- 是否启用字节码增强机制 --> lazyLoadingEnabled="true" <!-- 是否启用延迟加载机制 --> maxRequests="32" <!-- 最大并发请求数 --> maxSessions="10" <!-- 最大Session数 --> maxTransactions="5" <!-- 最大并发事务数 --> /> <!-- 定义了ibatis的事务管理器有3中(JDBC,JTA,EXTERNAL) --> <transactionManager type="JDBC"> <!-- type属性指定了数据源的链接类型,也有3种类型(SIMPLE,DBCP,JNDI) --> <dataSource type="SIMPLE"> <property name="JDBC.Driver" value="${driver}" /> <property name="JDBC.ConnectionURL" value="${url}" /> <property name="JDBC.Username" value="${user}" /> <property name="JDBC.Password" value="${password}" /> </dataSource> </transactionManager> <!-- 实体的映射文件 可以多个--> <sqlMap resource="com/sbw/entity/Student.xml" /> </sqlMapConfig> 

实体映射文件: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>  
<!-- 通过typeAlias使得我们在下面使用Student实体类的时候不需要写包名 -->
    <typeAlias alias="Student" type="com.sbw.entity.Student" />  

    <!-- id表示select里的sql语句,resultClass表示返回结果的类型 -->
    <select id="getAllStudents" resultClass="Student">  
        select * from student  
    </select>  

    <!-- parameterClass表示外部调用的参数类型 -->
    <select id="getStudentById" parameterClass="int" resultClass="Student">
        select * from student where id=#id#
    </select>


    <insert id="addStudent">
        insert into student(name,score) values(#name#,#score#)
        <!-- insert操作返回值 -->
        <selectKey resultClass="int" keyProperty="id">
            select @@identity as inserted
        </selectKey>
    </insert>

    <delete id="delAll">
        delete from student
    </delete>
    <delete id="delStudent" parameterClass="int">
        delete from student where id = #id#
    </delete>

    <update id="updateStudentById" parameterClass="Student">
        update student set name=#name#, score=#score# where id=#id#
    </update>
</sqlMap> 

测试类:IBatisDemo.java

package com.sbw.test;

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

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.sbw.entity.*;

public class IBatisDemo {  

    private static SqlMapClient sqlMapClient = null;

    public static void main(String[] args){  
        String config = "SqlMapConfig.xml"; 
        Reader reader = null;
        //读取胚子文件
        try {
            reader = Resources.getResourceAsReader(config);
            sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader); 
            reader.close();

            /* * 查找操作 */
            @SuppressWarnings("unchecked")
            List<Student> list1 = sqlMapClient.queryForList("getAllStudents");


            for(Student stu1 : list1){
                System.out.println(stu1.getId() + " " + stu1.getName() + " " + stu1.getScore());
            }

            @SuppressWarnings("unchecked")
            List<Student> list2 = sqlMapClient.queryForList("getStudentById", 2);
            for(Student stu2 : list2){
                System.out.println(stu2.getId() + " " + stu2.getName() + " " + stu2.getScore());
            }

            /* * 添加操作 */
            Student student3 = new Student();
            student3.setName("sbw");
            student3.setScore(100);
            Object object = sqlMapClient.insert("addStudent",student3);//返回刚插入数据的主键值
            System.out.println("添加学生信息的返回值:" + object);

            /* * 删除操作 */
            int deleteId = 1;
            int deleteCount = sqlMapClient.delete("delStudent",deleteId);
            System.out.println("删除数量:" + deleteCount);//返回删除的数量

            /* * 更新操作 */
            Student student4 = new Student();
            student4.setId(2);
            student4.setName("gaoya");
            student4.setScore(99);
            int updateCount = sqlMapClient.update("updateStudentById", student4);
            System.out.println("更新数量:" + updateCount);//返回更新数量
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  

    }  
} 

结果如图:

iBatis入门实例_第1张图片

你可能感兴趣的:(ibatis,实例)