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的配置文件
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;characterEncoding=UTF-8
8
username
=
root
9
password
=
root
10
(4) 建一个对应数据库表的User Object:
User.java
1package com.ibatis.db;
2
3import java.io.Serializable;
4import java.util.HashSet;
5import java.util.Set;
6/** *//**
7 *
8 */
9public class User implements Serializable {
10
11 private Integer id;
12
13 private String name;
14
15 private Integer sex;
16
17 /** *//** default constructor */
18 public User() {}
19
20 public Integer getId() {
21 return id;
22 }
23
24 public void setId(Integer id) {
25 this.id = id;
26 }
27
28 public String getName() {
29 return name;
30 }
31
32 public void setName(String name) {
33 this.name = name;
34 }
35
36 public Integer getSex() {
37 return sex;
38 }
39
40 public void setSex(Integer sex) {
41 this.sex = sex;
42 }
43}
44
45
(5) Sql Map 的映射文件
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
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
10public class MyAppSqlconfig {
11
12 private static final SqlMapClient sqlMapper ;
13
14 static{
15 try {
16 Reader reader;
17 String resource ="sqlMapConfig.xml";
18 reader = Resources.getResourceAsReader(resource);
19 sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);
20 reader.close();
21 } 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
29 public static SqlMapClient getSqlMapInstance() {
30 return sqlMapper;
31 }
32}
33
(7) 设计Dao
UserDao.java
1package com.ibatis.dao;
2
3import java.util.List;
4
5import com.ibatis.db.User;
6
7public 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
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;
9/** *//**
10 *
11 * @author zlh
12 *
13 */
14public class UserDaoImpl implements UserDao {
15
16 private SqlMapClient sqlMap ;
17
18
19 public void init(){
20 if(sqlMap == null){
21 sqlMap = MyAppSqlconfig.getSqlMapInstance();// as coded above
22}
23 }
24
25 /**//*
26 *
27 * @see com.ibatis.dao.UserDao#addUser(com.ibatis.db.User)
28 */
29
30 public int addUser(User user) {
31 init();
32 int num = 1;
33
34 try {
35 sqlMap.insert("insertUser", user);
36 } catch (SQLException e) {
37 num = -1;
38 e.printStackTrace();
39 }
40 return num;
41 }
42
43 /**//*
44 *
45 * @see com.ibatis.dao.UserDao#findUserArray()
46 */
47
48 public List<User> findUserArray() throws Exception {
49init();
50 List<User> users = sqlMap.queryForList("getUserList", null);
51 return users;
52 }
53
54 /**//*
55 *
56 * @see com.ibatis.dao.UserDao#findUserByName(java.lang.String)
57 */
58 public User findUserByName(String name) throws Exception {
59init();
60 User user = (User) sqlMap.queryForObject("getUser", name);
61 return user;
62 }
63
64 /**//*
65 *
66 * @see com.ibatis.dao.UserDao#removeUser(java.lang.Integer)
67 */
68
69 public int removeUser(Integer userId) throws Exception {
70init();
71 int num = sqlMap.delete("deleteUser", userId);
72 return num;
73 }
74
75 /**//*
76 *
77 * @see com.ibatis.dao.UserDao#updateUser(com.ibatis.db.User)
78 */
79
80 public int updateUser(User user) throws Exception {
81init();
82 int num = sqlMap.update("updateUser", user);
83 return num;
84 }
85
86 /**//*
87 *
88 * @see com.ibatis.dao.UserDao#findUserById(java.lang.Integer)
89 */
90 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测试类
UserTest.java
1import org.junit.Assert;
2import org.junit.Test;
3
4import com.ibatis.db.User;
5import com.ibatis.manager.UserManagers;
6
7public class UserTest{
8
9 @Test
10 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中指定字段的数据类型.