ibatis入门实例

iBatis 简介:

iBatis 是apache 的一个开源项目,一个O/R Mapping 解决方案,iBatis 最大的特点就是小巧,上手很快。如果不需要太多复杂的功能,iBatis 是能够满足你的要求又足够灵活的最简单的解决方案,现在的iBatis 已经改名为Mybatis 了。

官网为:http://www.mybatis.org/

 

搭建iBatis 开发环境:

1 、导入相关的jar 包,ibatis-2.3.0.677.jar 、mysql-connector-java-5.1.6-bin.jar

        2 、编写配置文件:

              Jdbc 连接的属性文件

              总配置文件, SqlMapConfig.xml

              关于每个实体的映射文件(Map 文件)

 

Demo :

Student.java:

package com.iflytek.entity;



import java.sql.Date;



/**

 * @author xudongwang 2011-12-31

 *

 *         Email:xdwangiflytek@gmail.com

 *

 */

public class Student {

    // 注意这里需要保证有一个无参构造方法,因为包括Hibernate在内的映射都是使用反射的,如果没有无参构造可能会出现问题

    private int id;

    private String name;

    private Date birth;

    private float score;



    public int getId() {

        return id;

    }



    public void setId(intid) {

        this.id = id;

    }



    public String getName() {

        return name;

    }



    public void setName(String name) {

        this.name = name;

    }



    public Date getBirth() {

        return birth;

    }



    public void setBirth(Date birth) {

        this.birth = birth;

    }



    public float getScore() {

        return score;

    }



    public void setScore(floatscore) {

        this.score = score;

    }



    @Override

    public String toString() {

        return "id=" + id + "\tname=" + name + "\tmajor=" + birth +"\tscore="

                + score + "\n";

    }



}

SqlMap.properties :

driver=com.mysql.jdbc.Driver

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

username=root

password=123

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.iflytek.entity.Student" />



    <!-- 这样以后改了sql,就不需要去改java代码了 -->

    <!-- id表示select里的sql语句,resultClass表示返回结果的类型 -->

    <select id="selectAllStudent"resultClass="Student">

        select * from

        tbl_student

    </select>



    <!-- parameterClass表示参数的内容 -->

    <!-- #表示这是一个外部调用的需要传进的参数,可以理解为占位符 -->

    <select id="selectStudentById"parameterClass="int" resultClass="Student">

        select * from tbl_student where id=#id#

    </select>



    <!-- 注意这里的resultClass类型,使用Student类型取决于queryForList还是queryForObject -->

    <select id="selectStudentByName"parameterClass="String"

        resultClass="Student">

        select name,birth,score from tbl_student where name like

        '%$name$%'

    </select>



    <insert id="addStudent"parameterClass="Student">

        insert into

        tbl_student(name,birth,score) values

        (#name#,#birth#,#score#);

        <selectKey resultClass="int"keyProperty="id">

            select @@identity as inserted

            <!-- 这里需要说明一下不同的数据库主键的生成,对各自的数据库有不同的方式: -->

            <!-- mysql:SELECT LAST_INSERT_ID() AS VALUE -->

            <!-- mssql:select @@IDENTITY as value -->

            <!-- oracle:SELECT STOCKIDSEQUENCE.NEXTVAL AS VALUE FROM DUAL -->

            <!-- 还有一点需要注意的是不同的数据库生产商生成主键的方式不一样,有些是预先生成 (pre-generate)主键的,如Oracle和PostgreSQL。

                有些是事后生成(post-generate)主键的,如MySQL和SQL Server 所以如果是Oracle数据库,则需要将selectKey写在insert之前 -->

        </selectKey>

    </insert>



    <delete id="deleteStudentById"parameterClass="int">

        <!-- #id#里的id可以随意取,但是上面的insert则会有影响,因为上面的name会从Student里的属性里去查找 -->

        <!-- 我们也可以这样理解,如果有#占位符,则ibatis会调用parameterClass里的属性去赋值 -->

        delete from tbl_student where id=#id#

    </delete>



    <update id="updateStudent"parameterClass="Student">

        update tbl_student set

        name=#name#,birth=#birth#,score=#score# where id=#id#

    </update>



</sqlMap>


说明:

如果xml 中没有ibatis 的提示,则window --> Preference--> XML-->XML Catalog---> 点击add

选择uri URI: 请选择本地文件系统上

iBatisDemo1/WebContent/WEB-INF/lib/sql-map-config-2.dtd 文件;

Key Type: 选择Schema Location;

Key: 需要联网的,不建议使用;

 

SqlMapConfig.xml :

01	<?xml version="1.0"encoding="UTF-8"?>
02	<!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
03	    "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
04	
05	<sqlMapConfig>
06	    <!-- 引用JDBC属性的配置文件 -->
07	    <properties resource="com/iflytek/entity/SqlMap.properties"/>
08	    <!-- 使用JDBC的事务管理 -->
09	    <transactionManager type="JDBC">
10	        <!-- 数据源 -->
11	        <dataSource type="SIMPLE">
12	            <property name="JDBC.Driver"value="${driver}" />
13	            <property name="JDBC.ConnectionURL"value="${url}" />
14	            <property name="JDBC.Username"value="${username}" />
15	            <property name="JDBC.Password"value="${password}" />
16	        </dataSource>
17	    </transactionManager>
18	    <!-- 这里可以写多个实体的映射文件 -->
19	    <sqlMap resource="com/iflytek/entity/Student.xml"/>
20	</sqlMapConfig>
StudentDao :
01	package com.iflytek.dao;
02	
03	import java.util.List;
04	
05	import com.iflytek.entity.Student;
06	
07	/**
08	 * @author xudongwang 2011-12-31
09	 *
10	 *         Email:xdwangiflytek@gmail.com
11	 *
12	 */
13	public interface StudentDao {
14	
15	    /**
16	     * 添加学生信息
17	     *
18	     * @param student
19	     *            学生实体
20	     * @return 返回是否添加成功
21	     */
22	    public boolean addStudent(Student student);
23	
24	    /**
25	     * 根据学生id删除学生信息
26	     *
27	     * @param id
28	     *            学生id
29	     * @return 删除是否成功
30	     */
31	    public boolean deleteStudentById(intid);
32	
33	    /**
34	     * 更新学生信息
35	     *
36	     * @param student
37	     *            学生实体
38	     * @return 更新是否成功
39	     */
40	    public boolean updateStudent(Student student);
41	
42	    /**
43	     * 查询全部学生信息
44	     *
45	     * @return 返回学生列表
46	     */
47	    public List<Student> selectAllStudent();
48	
49	    /**
50	     * 根据学生姓名模糊查询学生信息
51	     *
52	     * @param name
53	     *            学生姓名
54	     * @return 学生信息列表
55	     */
56	    public List<Student> selectStudentByName(String name);
57	
58	    /**
59	     * 根据学生id查询学生信息
60	     *
61	     * @param id
62	     *            学生id
63	     * @return 学生对象
64	     */
65	    public Student selectStudentById(intid);
66	
67	}

StudentDaoImpl :

001	package com.iflytek.daoimpl;
002	
003	import java.io.IOException;
004	import java.io.Reader;
005	import java.sql.SQLException;
006	import java.util.List;
007	
008	import com.ibatis.common.resources.Resources;
009	import com.ibatis.sqlmap.client.SqlMapClient;
010	import com.ibatis.sqlmap.client.SqlMapClientBuilder;
011	import com.iflytek.dao.StudentDao;
012	import com.iflytek.entity.Student;
013	
014	/**
015	 * @author xudongwang 2011-12-31
016	 *
017	 *         Email:xdwangiflytek@gmail.com
018	 *
019	 */
020	public class StudentDaoImpl implementsStudentDao {
021	
022	    private static SqlMapClient sqlMapClient =null;
023	
024	    // 读取配置文件
025	    static {
026	        try {
027	            Reader reader = Resources
028	                    .getResourceAsReader("com/iflytek/entity/SqlMapConfig.xml");
029	            sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
030	            reader.close();
031	        } catch (IOException e) {
032	            e.printStackTrace();
033	        }
034	    }
035	
036	    public boolean addStudent(Student student) {
037	        Object object = null;
038	        boolean flag = false;
039	        try {
040	            object = sqlMapClient.insert("addStudent", student);
041	            System.out.println("添加学生信息的返回值:"+ object);
042	        } catch (SQLException e) {
043	            e.printStackTrace();
044	        }
045	        if (object != null) {
046	            flag = true;
047	        }
048	        return flag;
049	    }
050	
051	    public boolean deleteStudentById(intid) {
052	        boolean flag = false;
053	        Object object = null;
054	        try {
055	            object = sqlMapClient.delete("deleteStudentById", id);
056	            System.out.println("删除学生信息的返回值:"+ object + ",这里返回的是影响的行数");
057	        } catch (SQLException e) {
058	            e.printStackTrace();
059	        }
060	        if (object != null) {
061	            flag = true;
062	
063	        }
064	        return flag;
065	
066	    }
067	
068	    public boolean updateStudent(Student student) {
069	        boolean flag = false;
070	        Object object = false;
071	        try {
072	            object = sqlMapClient.update("updateStudent", student);
073	            System.out.println("更新学生信息的返回值:"+ object + ",返回影响的行数");
074	        } catch (SQLException e) {
075	            e.printStackTrace();
076	        }
077	        if (object != null) {
078	            flag = true;
079	        }
080	        return flag;
081	    }
082	
083	    public List<Student> selectAllStudent() {
084	        List<Student> students = null;
085	        try {
086	            students = sqlMapClient.queryForList("selectAllStudent");
087	        } catch (SQLException e) {
088	            e.printStackTrace();
089	        }
090	        return students;
091	    }
092	
093	    public List<Student> selectStudentByName(String name) {
094	        List<Student> students = null;
095	        try {
096	            students = sqlMapClient.queryForList("selectStudentByName",name);
097	        } catch (SQLException e) {
098	            e.printStackTrace();
099	        }
100	        return students;
101	    }
102	
103	    public Student selectStudentById(intid) {
104	        Student student = null;
105	        try {
106	            student = (Student) sqlMapClient.queryForObject(
107	                    "selectStudentById", id);
108	        } catch (SQLException e) {
109	            e.printStackTrace();
110	        }
111	        return student;
112	    }
113	}

TestIbatis.java :

01	package com.iflytek.test;
02	
03	import java.sql.Date;
04	import java.util.List;
05	
06	import com.iflytek.daoimpl.StudentDaoImpl;
07	import com.iflytek.entity.Student;
08	
09	/**
10	 * @author xudongwang 2011-12-31
11	 *
12	 *         Email:xdwangiflytek@gmail.com
13	 *
14	 */
15	public class TestIbatis {
16	
17	    public static void main(String[] args) {
18	        StudentDaoImpl studentDaoImpl = newStudentDaoImpl();
19	
20	        System.out.println("测试插入");
21	        Student addStudent = new Student();
22	        addStudent.setName("李四");
23	        addStudent.setBirth(Date.valueOf("2011-09-02"));
24	        addStudent.setScore(88);
25	        System.out.println(studentDaoImpl.addStudent(addStudent));
26	
27	        System.out.println("测试根据id查询");
28	        System.out.println(studentDaoImpl.selectStudentById(1));
29	
30	        System.out.println("测试模糊查询");
31	        List<Student> mohuLists = studentDaoImpl.selectStudentByName("李");
32	        for (Student student : mohuLists) {
33	            System.out.println(student);
34	        }
35	
36	        System.out.println("测试查询所有");
37	        List<Student> students = studentDaoImpl.selectAllStudent();
38	        for (Student student : students) {
39	            System.out.println(student);
40	        }
41	
42	        System.out.println("根据id删除学生信息");
43	        System.out.println(studentDaoImpl.deleteStudentById(1));
44	
45	        System.out.println("测试更新学生信息");
46	        Student updateStudent = new Student();
47	        updateStudent.setId(1);
48	        updateStudent.setName("李四1");
49	        updateStudent.setBirth(Date.valueOf("2011-08-07"));
50	        updateStudent.setScore(21);
51	        System.out.println(studentDaoImpl.updateStudent(updateStudent));
52	
53	    }
54	}


iBatis 的优缺点:

优点:

1、 减少代码量,简单;

2、 性能增强;

3、 Sql 语句与程序代码分离;

4、 增强了移植性;

缺点:

1、 和Hibernate 相比,sql 需要自己写;

2、 参数数量只能有一个,多个参数时不太方便;
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值