Ibatis 的简单应用

系统 1474 0
     可能有些人 都用上了Mybatis, 但是有的公司 可能还在用ibatis.
Ibatis-Home(官网) 想了解更多的 就看看.

myeclipse 插件地址
http://ibatis.apache.org/tools/abator

Ibatis的优点(与JDBC相比)
1.减少了约61%代码量
2.配置 使用简单
3.架构性能增强
4.SQL 语句和程序代码分离
5.简化项目中的分工
6.增强移植性


下面开始 简单应用 (CRUD)
1.使用的jar 
  ibatis-2.3.4.726.jar (ibatis就用这个jar就可以了)
  ojdbc6.jar (oracle 的驱动)


SqlMapConfig.properties
    
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
username=test
password=test

  


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>

  <!-- Configure a built-in transaction manager.  If you're using an 
       app server, you probably want to use its transaction manager 
       and a managed datasource -->
  <properties resource="SqlMapConfig.properties"/>
  <transactionManager type="JDBC" commitRequired="false">
    <dataSource type="SIMPLE">
      <property name="JDBC.Driver" value="${driver}"/>
      <property name="JDBC.ConnectionURL" value="${url}"/>
      <property name="JDBC.Username" value="${username}"/>
      <property name="JDBC.Password" value="${password}"/>
    </dataSource>
  </transactionManager>

  <!-- List the SQL Map XML files. They can be loaded from the 
       classpath, as they are here (com.domain.data...) -->
  <sqlMap resource="com/ibatis/student/Student.xml"/>
  <!-- List more here...
  <sqlMap resource="com/mydomain/data/Order.xml"/>
  <sqlMap resource="com/mydomain/data/Documents.xml"/>
  -->

</sqlMapConfig>



  


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 alias="Student" type="com.ibatis.student.Student"/>
    
    <select id="queryAllStudent" resultClass="Student">
    	select * from student
    </select>
    
    <select id="queryStudentById" parameterClass="int" resultClass="Student">
		select * from student where sid=#sid#    
    </select>
    
    <!-- 这个里面的 占位符 就不能乱写了 因为会调用 Student 的 getSid ...getSname() ..  -->
    <insert id="addStudent" parameterClass="Student">
    	insert into student(sid,sname,major,birth,score) 
    	values    (#sid#,#sname#,#major#,#birth#,#score#)
    </insert>
      
    <!-- #sid# 这个 只是一个占位符 可以更改的 -->
    <delete id="deleteStudentById" parameterClass="int">
    	delete from student where sid=#sid#
    </delete>
    
    
    <update id="updateStudent" parameterClass="Student">
    	update student
    	set 
    		sname=#sname#,
    		major=#major#,
    	    birth=#birth#,
    	    score=#score#
    	 where sid=#sid#
    </update>
    
    <!-- 如果参数  要拼接成一个表达式 就要将#  换成  $ -->
    <select id="queryStudentByName" parameterClass="String" resultClass="Student">
    	select sid,sname,major,birth,score from student where sname like '$sname$'	
    </select>  
    
    <!-- Student  不区分大小写的   -->
    <insert id="insertStudentBySequence" parameterClass="Student">
    	<selectKey resultClass="int" keyProperty="sid">
    		select STUDENT_SEQ.nextVal from dual
    	</selectKey>
    	insert into student(sid,sname,major,birth,score)
    	values (#sid#,#sname#,#major#,#birth#,#score#)
    </insert>


    	
</sqlMap>


  


IStudentDAO.java
    
package com.ibatis.student;

import java.util.List;


public interface IStudentDAO {
	public void addStudent(Student student);

	//使用自动增长 主键 
	public void addStudentBySequence(Student student);

	public void delStudentById(int id);

	public void updStudentById(Student student);

	
	public List<Student> queryAllStudent();

	//使用模糊查询
	public List<Student> queryStudentByName(String name);

	public Student queryStudentById(int id);
}


  


IStudentDAOImpl.java
    
package com.ibatis.student;


import java.io.IOException;
import java.io.Reader;
import java.sql.Date;
import java.sql.SQLException;
import java.util.List;

import com.ibatis.sqlmap.client.SqlMapClient;

public class IStudentDAOImpl implements IStudentDAO {

	private static SqlMapClient sqlMapClient=null;
	
	static{
		try {
			Reader reader=com.ibatis.common.resources.Resources.getResourceAsReader("SqlMapConfig.xml");
			sqlMapClient=com.ibatis.sqlmap.client.SqlMapClientBuilder.buildSqlMapClient(reader);
			reader.close();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void addStudent(Student student) {
		// TODO Auto-generated method stub
		try {
			sqlMapClient.insert("addStudent", student);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void addStudentBySequence(Student student) {
		// TODO Auto-generated method stub
		try {
			//1.从数据库徐磊中获取主键值
			//2.往 student表中插入记录
			sqlMapClient.insert("insertStudentBySequence", student);
			System.err.println(student.getSid());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
	}

	public void delStudentById(int id) {
		// TODO Auto-generated method stub
		try {
			System.out.println(sqlMapClient.delete("deleteStudentById", id));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public List<Student> queryAllStudent() {
		// TODO Auto-generated method stub
		List<Student>  studentList=null;
		try {
			studentList=sqlMapClient.queryForList("queryAllStudent");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return studentList;
	}

	public Student queryStudentById(int id) {
		Student student=null;
		try {
			student=(Student)sqlMapClient.queryForObject("queryStudentById",id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return student;
	}

	public List<Student> queryStudentByName(String name) {
		// TODO Auto-generated method stub
		List<Student> studentList=null;
		try {
			studentList=sqlMapClient.queryForList("queryStudentByName", name);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return studentList;
	}

	public void updStudentById(Student student) {
		// TODO Auto-generated method stub
		try {
			System.out.println(sqlMapClient.update("updateStudent", student));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public  static void main(String [] args){
		IStudentDAO dao=new IStudentDAOImpl();
		//1.
		
//		for (Student student : dao.queryAllStudent()) {
//			System.out.println(student);
//		}
		
		//2.
//		System.out.println(dao.queryStudentById(1));
		
		//3.
//		Student student=new Student();
//		student.setSid(5);
//		student.setSname("admin");
//		student.setScore(100);
//		student.setMajor("Games");
//		student.setBirth(Date.valueOf("2008-08-08"));
//		
//		dao.addStudent(student);
		
		//4.
//		dao.delStudentById(1);
		
		//5.
//		Student student=new Student();
//		student.setSid(2);
//		student.setSname("luob");
//		student.setScore(50);
//		student.setMajor("Games");
//		student.setBirth(Date.valueOf("2008-08-08"));
//		dao.updStudentById(student);
		
		//6.
//		for (Student student : dao.queryStudentByName("l%")) {
//			System.out.println(student);
//		}
		
		//7.
		Student student=new Student();
		student.setSid(2);
		student.setSname("SMITH");
		student.setScore(50);
		student.setMajor("Games");
		student.setBirth(Date.valueOf("2008-08-08"));
		
		dao.addStudentBySequence(student);
	}


}



  


    
ibatis in语句参数传入方法
Posted on 2012-02-03 10:11 yuhaibo736 阅读(2925) 评论(1)  编辑  收藏  
 第一种:传入参数仅有数组 
       <select id="GetEmailList_Test"  resultClass="EmailInfo_"> 
            select * 
            from MailInfo with (nolock) 
            where ID in 
                <iterate open="(" close=")" conjunction="," > 
                    #[]# 
                </iterate> 
        </select> 
调用 
            string[] strValue = new string[] { "1", "2", "3" }; 
            Reader.QueryForList<EmailInfoModel>("WebApp_Ibatisnet.dao.GetEmailList_Test", strValue ); 

       第二种:传入参数有数组,且有其他数据 
        <select id="GetEmailList_Test3" parameterClass="TestIn" resultClass="EmailInfo_"> 
            select  top(#Count#)* 
            from MailInfo with (nolock) 
            where ID in 
            <iterate open="(" close=")" conjunction="," property="ArrValue" > 
                #ArrValue[]# 
            </iterate> 
        </select> 
调用 
            TestIn ti = new TestIn(); 
            ti.Count = 1; 
            ti.ArrValue = strValue; 
            return Reader.QueryForList<EmailInfoModel>("WebApp_Ibatisnet.dao.GetEmailList_Test3", ti); 
实体类: 
   public class TestIn 
    { 
        private int count; 
        public int Count 
        { 
            get { return count; } 
            set { count = value; } 
        } 
        private string[] arrValue; 
        public string[] ArrValue 
        { 
            get { return arrValue; } 
            set { arrValue = value; } 
        } 
    } 

       第三种:in后面的数据确定,使用string传入 
        <select id="GetEmailList_Test2" parameterClass="TestIn" resultClass="EmailInfo_"> 
            select * 
            from MailInfo with (nolock) 
            where ID in 
            ($StrValue$) 
        </select> 
调用 
                Reader.QueryForList<EmailInfoModel>("WebApp_Ibatisnet.dao.GetEmailList_Test2", "1,2,3"); 

<!--
其他信息: 
Iterate的属性: 
prepend -可被覆盖的SQL语句组成部分,添加在语句的前面(可选) 
property -类型为java.util.List的用于遍历的元素(必选) 
open -整个遍历内容体开始的字符串,用于定义括号(可选) 
close -整个遍历内容体结束的字符串,用于定义括号(可选) 
conjunction -每次遍历内容之间的字符串,用于定义AND或OR(可选) 
<iterate>遍历类型为java.util.List的元素。-->

<!--like-->
<select id="selectAccount" resultMap="AccountResult" parameterClass="Account">
select * from ACCOUNT
<dynamic prepend="where">
<isNotNull property="id" prepend="and" open="(" close=")">
id = #id#
</isNotNull>
<isNotEmpty property="name" prepend="and">
name like '%$name$%'
</isNotEmpty>
</dynamic>
</select>


  


Ibatis 的简单应用


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论