【ibatis学习笔记】 1 入门

【ibatis学习笔记】- 1 - 入门

0、简介

  网上已经有很多ibatis的教程与例子,在此自己把自己学习Ibatis的经历都记录下来。知识需要记录与沉淀。整个学习笔记都将围绕学生管理系统来完成。

1、入门

  在入门篇中,新建了一个学生表,然后实现对学生表的查询。通过入门篇来大概的看看Ibatis的基本使用。

2、Jar包

3、持久化对象(Student)

package org.samuel.ibatis.student;
public class Student {
    
    private int id;
    
    private String name;
    
    private int age;

    //省略get、set方法
}

4、Sqlmap映射文件(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.samuel.ibatis.student.Student" />

    <select id="findById" resultClass="student" parameterClass="integer">
        <![CDATA[
            SELECT * FROM t_student WHERE id=#id#
        ]]>
    </select>

</sqlMap>

5、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>
    <settings 
        cacheModelsEnabled="true"
        enhancementEnabled="true"
        lazyLoadingEnabled="true"
        maxRequests="32"
        maxSessions="10"
        maxTransactions="5"
        useStatementNamespaces="true" />
    
    <transactionManager type="JDBC" >
      <dataSource type="SIMPLE">
        <property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
        <property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost:3306/student"/>
        <property name="JDBC.Username" value="root"/>
        <property name="JDBC.Password" value="root"/>
      </dataSource>
   </transactionManager>
        
    <sqlMap resource="org/samuel/ibatis/student/Student.xml" />
    
</sqlMapConfig>

6、主函数

public static void main(String[] args) {
        String resource = "SqlMapConfig.xml";
        try {
            Reader reader = Resources.getResourceAsReader(resource);
            SqlMapClient mapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
            Student s =  (Student) mapClient.queryForObject("Student.findById", 1);
        } catch (Exception e) {
            e.printStackTrace();
        } 
}

7、构建数据库

  使用navicat新建student数据库,然后添加表t_student

原文地址:https://www.cnblogs.com/onliny/p/2627210.html