iBatis 学习笔记(1) 入门

<?xml version="1.0" encoding="UTF-8" ?>              17:58:56

昨天网络上看了一些关于IBATIS的内容,今天开始进入具体的学习期.

1.  下载IBATIS 2.3.4的软件包(http://ibatis.apache.org)。

2.  Mysql里建 数据库:ibatis_db和表t_user

Int id , varchar name, int sex.

操作如下:

create database ibatis_db;

show databases;

create table ibatis_db.t_user(id int(6) not null,

name varchar(15) not null, sex int(1));

 

3.  eclipse里建工程ibatisItem

(1)     导入lib

ibatis-2.3.4.726.jar

mysql-connector-java-5.0.8-bin.jar

(2)     sqlMap的配置文件

 

ContractedBlock.gif ExpandedBlockStart.gif sqlMapConfig.xml
 1<?xml version="1.0" encoding="UTF-8" ?>
 2
 3<!DOCTYPE sqlMapConfig      
 4    PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"      
 5    "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
 6   
 7    <sqlMapConfig>
 8    
 9         <properties resource="sqlMapConfig.properties" />
10         
11         <settings 
12             cacheModelsEnabled="true"
13             enhancementEnabled="true"
14             lazyLoadingEnabled="true"
15             errorTracingEnabled="true"
16             maxRequests="32"
17             maxSessions="10"
18             maxTransactions="5"
19             useStatementNamespaces="false"
20         />
21         <transactionManager type="JDBC">
22            <dataSource type="SIMPLE">
23                <property name="JDBC.Driver" value="${driver}"></property>
24                <property name="JDBC.ConnectionURL" value="${url}" ></property>
25                <property name="JDBC.Username" value="${username}" ></property>
26                <property name="JDBC.Password" value="${password}" />
27            </dataSource>
28         </transactionManager>
29         
30         <sqlMap resource="com/ibatis/db/xml/User.xml" />
31    </sqlMapConfig>

 

(3)      sqlMapConfig.properties

 

 1  #This is just a simple properties file that simplifies automated configuration
 2  #of the SQL Maps configuration file (e.g. by Ant builders or continuous
 3  #Integration tools  for  different environments .etc.)
 4  #These values can be used in any property value in the file above(e.g  " ${driver} " )
 5  #Using a properties file such as  this  is completely optional.
 6  driver = com.mysql.jdbc.Driver
 7  url = jdbc:mysql: // localhost:3306/ibatis_db?userUnicode=true&amp;amp;characterEncoding=UTF-8
 8  username = root
 9  password = root
10 

 

(4)     建一个对应数据库表的User Object:

 

ContractedBlock.gif ExpandedBlockStart.gif User.java
 1package com.ibatis.db;
 2
 3import java.io.Serializable;
 4import java.util.HashSet;
 5import java.util.Set;
 6ExpandedBlockStart.gifContractedBlock.gif/** *//**
 7 * 
 8 */

 9ExpandedBlockStart.gifContractedBlock.gifpublic class User implements Serializable {
10
11    private Integer id;
12    
13    private String name;
14    
15    private Integer sex;
16    
17ExpandedSubBlockStart.gifContractedSubBlock.gif    /** *//** default constructor */
18ExpandedSubBlockStart.gifContractedSubBlock.gif    public User() {}
19
20ExpandedSubBlockStart.gifContractedSubBlock.gif    public Integer getId() {
21        return id;
22    }

23
24ExpandedSubBlockStart.gifContractedSubBlock.gif    public void setId(Integer id) {
25        this.id = id;
26    }

27
28ExpandedSubBlockStart.gifContractedSubBlock.gif    public String getName() {
29        return name;
30    }

31
32ExpandedSubBlockStart.gifContractedSubBlock.gif    public void setName(String name) {
33        this.name = name;
34    }

35
36ExpandedSubBlockStart.gifContractedSubBlock.gif    public Integer getSex() {
37        return sex;
38    }

39
40ExpandedSubBlockStart.gifContractedSubBlock.gif    public void setSex(Integer sex) {
41        this.sex = sex;
42    }

43}

44
45

 

(5)     Sql Map 的映射文件

ContractedBlock.gif ExpandedBlockStart.gif User.xml
 1<?xml version="1.0" encoding="UTF-8"?>
 2
 3<!DOCTYPE sqlMap      
 4    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      
 5    "http://ibatis.apache.org/dtd/sql-map-2.dtd">
 6
 7<sqlMap namespace="User">
 8
 9  <!-- Use type aliases to avoid typing the full classname every time. -->
10  <typeAlias alias="User" type="com.ibatis.db.User"/>
11  
12   <select id="getUser"
13       parameterClass="java.lang.String"
14       resultClass="user">
15       <![CDATA[ select id,name, sex from t_user where name = #name#
16       ]]>
17    </select>
18    
19       <select id="getUserById"
20       parameterClass="java.lang.Integer"
21       resultClass="user">
22       <![CDATA[ select id,name, sex from t_user where id = #id#
23       ]]>
24    </select>
25    
26    <update id="updateUser"
27       parameterClass="user">
28       <![CDATA[ update t_user set name=#name#, sex=#sex# where id = #id#
29       ]]>
30    </update>
31    
32     <insert id="insertUser"
33       parameterClass="user">
34       INSERT INTO t_user(id,name,sex) VALUES(#id#,#name#,#sex#)
35     </insert>
36     
37     <select id="getUserList" resultClass="user">
38        <![CDATA[ select id,name,sex from t_user group by id ]]>
39    </select>
40    
41     <delete id="deleteUser"
42       parameterClass="java.lang.Integer">
43         <![CDATA[delete from t_user where id = #id#]]>
44    </delete>
45  
46</sqlMap>

 

(6)     设计一个类MyAppSqlconfig.java

 

ContractedBlock.gif ExpandedBlockStart.gif MyAppSqlconfig.java
 1package com.ibatis.dao.common;
 2
 3import java.io.IOException;
 4import java.io.Reader;
 5
 6import com.ibatis.common.resources.Resources;
 7import com.ibatis.sqlmap.client.SqlMapClient;
 8import com.ibatis.sqlmap.client.SqlMapClientBuilder;
 9
10ExpandedBlockStart.gifContractedBlock.gifpublic class MyAppSqlconfig {
11    
12    private  static final SqlMapClient sqlMapper ;
13    
14ExpandedSubBlockStart.gifContractedSubBlock.gif    static{
15ExpandedSubBlockStart.gifContractedSubBlock.gif          try {
16            Reader reader;
17            String resource ="sqlMapConfig.xml";
18            reader = Resources.getResourceAsReader(resource);
19            sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);
20            reader.close();
21ExpandedSubBlockStart.gifContractedSubBlock.gif          }
 catch (IOException e) {
22              // TODO Auto-generated catch block
23              e.printStackTrace();
24             
25              throw new RuntimeException("Error initializing MyAppSqlconfig class.Cause:" + e);
26        }
 
27    }

28    
29ExpandedSubBlockStart.gifContractedSubBlock.gif    public static SqlMapClient getSqlMapInstance() {
30        return sqlMapper;
31    }

32}

33

 

(7)     设计Dao


ContractedBlock.gif ExpandedBlockStart.gif UserDao.java
 1package com.ibatis.dao;
 2
 3import java.util.List;
 4
 5import com.ibatis.db.User;
 6
 7ExpandedBlockStart.gifContractedBlock.gifpublic interface UserDao {
 8    
 9    public int addUser(User user) throws Exception;
10    
11    public int removeUser(Integer userId) throws Exception;
12    
13    public int updateUser(User user) throws Exception;
14    
15    public List<User> findUserArray() throws Exception;
16    
17    public User findUserById(Integer userId) throws Exception;
18    
19    public User findUserByName(String name) throws Exception ;
20
21}

22

 

 

 

ContractedBlock.gif ExpandedBlockStart.gif UserDaoImpl.java
 1package com.ibatis.dao.impl;
 2
 3import java.sql.SQLException;
 4import java.util.List;
 5import com.ibatis.dao.UserDao;
 6import com.ibatis.dao.common.MyAppSqlconfig;
 7import com.ibatis.db.User;
 8import com.ibatis.sqlmap.client.SqlMapClient;
 9ExpandedBlockStart.gifContractedBlock.gif/** *//**
10 * 
11 * @author zlh
12 *
13 */

14ExpandedBlockStart.gifContractedBlock.gifpublic class UserDaoImpl implements UserDao {
15    
16    private SqlMapClient sqlMap ;
17    
18    
19ExpandedSubBlockStart.gifContractedSubBlock.gif    public void init(){
20ExpandedSubBlockStart.gifContractedSubBlock.gif        if(sqlMap == null){
21            sqlMap = MyAppSqlconfig.getSqlMapInstance();// as coded above
22}

23    }

24    
25ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//*
26     * 
27     * @see com.ibatis.dao.UserDao#addUser(com.ibatis.db.User)
28     */

29    
30ExpandedSubBlockStart.gifContractedSubBlock.gif    public int addUser(User user)  {
31        init();
32        int num = 1;
33        
34ExpandedSubBlockStart.gifContractedSubBlock.gif        try {
35          sqlMap.insert("insertUser", user);
36ExpandedSubBlockStart.gifContractedSubBlock.gif        }
 catch (SQLException e) {
37            num = -1;
38            e.printStackTrace();
39        }

40        return num;
41    }

42
43ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//*
44     * 
45     * @see com.ibatis.dao.UserDao#findUserArray()
46     */

47    
48ExpandedSubBlockStart.gifContractedSubBlock.gif    public List<User> findUserArray() throws Exception {
49init();
50        List<User> users = sqlMap.queryForList("getUserList"null);
51        return users;
52    }

53
54ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//*
55     * 
56     * @see com.ibatis.dao.UserDao#findUserByName(java.lang.String)
57     */

58ExpandedSubBlockStart.gifContractedSubBlock.gif    public User findUserByName(String name) throws Exception {
59init();
60        User user = (User) sqlMap.queryForObject("getUser", name);
61        return user;
62    }

63
64ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//*
65     * 
66     * @see com.ibatis.dao.UserDao#removeUser(java.lang.Integer)
67     */

68    
69ExpandedSubBlockStart.gifContractedSubBlock.gif    public int removeUser(Integer userId) throws Exception {
70init();
71        int num =  sqlMap.delete("deleteUser", userId);
72        return num;
73    }

74
75ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//*
76     * 
77     * @see com.ibatis.dao.UserDao#updateUser(com.ibatis.db.User)
78     */

79    
80ExpandedSubBlockStart.gifContractedSubBlock.gif    public int updateUser(User user) throws Exception {
81init();
82        int num =  sqlMap.update("updateUser", user);
83        return num;
84    }

85
86ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//*
87     * 
88     * @see com.ibatis.dao.UserDao#findUserById(java.lang.Integer)
89     */

90ExpandedSubBlockStart.gifContractedSubBlock.gif    public User findUserById(Integer userId) throws Exception {
91        init();
92        User user = (User) sqlMap.queryForObject("getUserById", userId);
93        return user;
94    }

95
96}

97

 

 

最后写一个junit测试类

 

ContractedBlock.gifExpandedBlockStart.gifUserTest.java
 1import org.junit.Assert;
 2import
 org.junit.Test;
 3

 4import
 com.ibatis.db.User;
 5import
 com.ibatis.manager.UserManagers;
 6

 7ExpandedBlockStart.gifContractedBlock.gifpublic class UserTest
{
 8

 9
    @Test
10ExpandedSubBlockStart.gifContractedSubBlock.gif    public void TestCase() throws Exception 
{
11        private UserDao dao = new
 UserDaoImpl();
12        User newUser = new
 User();
13        newUser.setId(new Integer(100
));
14        newUser.setName("User100"
);
15        newUser.setSex(1
);
16        int num =
 dao.addUser(newUser);
17        Assert.assertEquals(num, 1
);
18
        
19        User user = dao.findUserById(new Integer(100
));
20        Assert.assertEquals(user.getId(), new Integer(100
));
21

22    }

23}

24

 

    顺利完成!

 

    总结一下,在今天的学习过程中.容易出错的在Sql Map 的映射文件.

   1) 在parameterMap 和resultMap中,字段数据类型是java.sqlTypes类定义的常量名称.BLOB,CHAR,CLOB,DATE,LONGVARBINARY,INTEGER,NULL,NUMBRIC,TIME

TIMESTAMP和VARCHAR等.

  2)对于数据表中的NULLBALE的字段,必须在parameterMap 和resultMap中指定字段的数据类型.










转载于:https://www.cnblogs.com/JavaVillage/archive/2008/11/28/1343334.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值