ibatis 学习笔记 包括第一个例子

来源:互联网 发布:恐怖小说推荐知乎 编辑:程序博客网 时间:2024/04/30 08:16

好久没写blog了。近日在学ibatis,下个项目要用了。现在把一些学习笔记整理在这里。

 1.       目前的框架,不论是ORM的还是其它大都利用xml来解耦合。更加符合OO的思想,ibatis也不例外。其运行流程如下:  

          DAO(其它主体如jsp或service)-------读取------>ibatis的config.xml(文件内包括 javabean和属性文件的映射)-----解析----à通过文件与bean的映射来解析对应关系

      读取一般利用java.io.Reader.片段如下:       

  Reader reader = Resources.getResourceAsReader(“config.xml”);  

    送给ibatis解析config.xml  

      SqllMapClient sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);  

 如果config.xml和属性映射文件正确的话就ok了,可以利用Dao来访问了。Config.xml 和属性文件如下:  

 <!--  config.xml   --> 

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE sqlMapConfigPUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN""http://www.ibatis.com/dtd/sql-map-config-2.dtd"><sqlMapConfig><settings cacheModelsEnabled="true" enhancementEnabled="true"lazyLoadingEnabled="true" errorTracingEnabled="true" maxRequests="32"maxSessions="10" maxTransactions="5" useStatementNamespaces="false" /><transactionManager type="JDBC"><dataSource type="SIMPLE"><property name="JDBC.Driver"value="net.sourceforge.jtds.jdbc.Driver" /><property name="JDBC.ConnectionURL"value="jdbc:jtds:sqlserver://localhost:1433/ibatis" /><property name="JDBC.Username" value="sa" /><property name="JDBC.Password" value="1234" /></dataSource></transactionManager><sqlMap resource="com/luyu/ibatis/User.xml" /></sqlMapConfig>
 <!--  属性文件.xml   --> 
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE sqlMapPUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN""http://www.ibatis.com/dtd/sql-map-2.dtd"><sqlMap namespace="User"><typeAlias alias="user" type="com.luyu.ibatis.bean.User" /><select id="getUser" parameterClass="java.lang.String"resultClass="user"><![CDATA[selectname,sexfrom t_userwhere name = #name#]]></select><select   id="findAllUser" resultClass="user"><![CDATA[selectname,sexfrom t_user]]></select><update id="updateUser" parameterClass="user"><![CDATA[UPDATE t_userSETname=#name#,sex=#sex#WHERE id = #id#]]></update><insert id="insertUser" parameterClass="user">INSERT INTO t_user ( name, sex) VALUES ( #name#, #sex# )</insert><delete id="deleteUser" parameterClass="java.lang.String">delete from t_user where id = #value#</delete></sqlMap>
 
   Dao中的第一个让问如下:    
 public static List<User> selectAllAccounts () throws SQLException {   
      return sqlMapper.queryForList("findAllUser");  
}   

共有2个jar

 1.jdts对sqlserver2000的jar

2.    ibatis2.3.2.715.jar      

所有代码如下:

User.java

package com.luyu.ibatis.bean;import java.io.Serializable;public class User implements Serializable{private int id;private int sex;private String name = "";public User() {}public User(int id, int sex, String name) {super();this.id = id;this.sex = sex;this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public int getSex() {return sex;}public void setSex(int sex) {this.sex = sex;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + id;result = prime * result + ((name == null) ? 0 : name.hashCode());result = prime * result + sex;return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;final User other = (User) obj;if (id != other.id)return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;if (sex != other.sex)return false;return true;}}
UserDao.java
package com.luyu.ibatis.dao;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.luyu.ibatis.bean.User;public class UserDao {private static SqlMapClient sqlMapper;static {try {Reader reader = Resources.getResourceAsReader("com/luyu/ibatis/ibatisConfig.xml");sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);reader.close();} catch (IOException e) {// Fail fast.throw new RuntimeException("Something bad happened while building the SqlMapClient instance."+ e, e);}} public static List<User> selectAllAccounts () throws SQLException { return sqlMapper.queryForList("findAllUser"); }}
 
ibatisConfig.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE sqlMapConfigPUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN""http://www.ibatis.com/dtd/sql-map-config-2.dtd"><sqlMapConfig><settings cacheModelsEnabled="true" enhancementEnabled="true"lazyLoadingEnabled="true" errorTracingEnabled="true" maxRequests="32"maxSessions="10" maxTransactions="5" useStatementNamespaces="false" /><transactionManager type="JDBC"><dataSource type="SIMPLE"><property name="JDBC.Driver"value="net.sourceforge.jtds.jdbc.Driver" /><property name="JDBC.ConnectionURL"value="jdbc:jtds:sqlserver://localhost:1433/ibatis" /><property name="JDBC.Username" value="sa" /><property name="JDBC.Password" value="1234" /></dataSource></transactionManager><sqlMap resource="com/luyu/ibatis/User.xml" /></sqlMapConfig>
User.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE sqlMapPUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN""http://www.ibatis.com/dtd/sql-map-2.dtd"><sqlMap namespace="User"><typeAlias alias="user" type="com.luyu.ibatis.bean.User" /><select id="getUser" parameterClass="java.lang.String"resultClass="user"><![CDATA[selectname,sexfrom t_userwhere name = #name#]]></select><select   id="findAllUser" resultClass="user"><![CDATA[selectname,sexfrom t_user]]></select><update id="updateUser" parameterClass="user"><![CDATA[UPDATE t_userSETname=#name#,sex=#sex#WHERE id = #id#]]></update><insert id="insertUser" parameterClass="user">INSERT INTO t_user ( name, sex) VALUES ( #name#, #sex# )</insert><delete id="deleteUser" parameterClass="java.lang.String">delete from t_user where id = #value#</delete></sqlMap>
Test.java
package com.luyu.ibatis;import java.sql.SQLException;import java.util.List;import com.luyu.ibatis.bean.User;import com.luyu.ibatis.dao.UserDao;public class Test {public static void main(String[] args) {try {List<User> list = UserDao.selectAllAccounts();System.out.println(list.size());for (int i = 0; i < list.size(); i++) {System.out.println(list.get(i).getName());}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
 
哈哈。第一天就这么多了。明天继续。是比hibernate简单。
原创粉丝点击