ibatis框架的srud

iBatis 简介: 

iBatis 是apache 的一个开源项目,一个O/R Mapping 解决方案,iBatis 最大的特点就是小巧,上手很快。如果不需要太多复杂的功能,iBatis 是能够满足你的要求又足够灵活的最简单的解决方案,现在的iBatis 已经改名为Mybatis 了。

官网为:http://www.mybatis.org/

 

 

搭建iBatis 开发环境:

1 、导入相关的jar 包,ibatis-2.3.0.677.jar 、mysql-connector-java-5.1.17-bin.jar

 

2、编写实体类:Student.java

 
 
package com.zeng.entity;

import java.sql.Date;

/**
 * 学生类
 * @author lenovo
 *
 */
public class Student {

	private int id;		 //学号
	private String name; //姓名
	private Date birth;  //出生日期
	private float score; //成绩
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getBirth() {
		return birth;
	}
	public void setBirth(Date birth) {
		this.birth = birth;
	}
	public float getScore() {
		return score;
	}
	public void setScore(float score) {
		this.score = score;
	}
	
	
}


 

3.编写JDBC属性文件 :SqlMap.properties

 

driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/myschool
username=root
password=


 

4.编写实体映射文件 :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 使得我们在下面使用Student实体类时不再需要导入包名 -->
  <typeAlias alias="Student" type="com.zeng.entity.Student"/>   
  
  <!-- ibatis通过XML文件写 SQL诗句,有利于以后对SQL语句的修改, -->
  <!-- id:表示 sql 语句的 key , resultClass:表示返回结果的类型 -->
  <select id="selectAllStudent" resultClass="Student">
  select * from student
  </select>
  
  <!--
   parameterClass:表示参数类型  
   #id# :占位符
   -->
  <select id="selectStudentById" parameterClass="int" resultClass="Student">
   select * from student where id =#id#
  </select>
  
  <!-- 注意这里的 resultClass的类型,使用 Student 取决于使用 queryForList 还是 queryForObject -->
 <select id="selectStudentByName" parameterClass="String" resultClass="Student">
  select name,birth,score from student where name like '%$name$%'
 </select>
  
 <insert id="addStudent" parameterClass="Student">
 insert into 
 Student(name,birth,score) 
 values(#name#,#birth#,#score#);
 <selectKey resultClass="int" keyProperty="id">
  select @@identity as inserted 
<!-- 这里需要说明一下不同的数据库主键的生成,对各自的数据库有不同的方式: --> 
<!-- mysql:SELECT LAST_INSERT_ID() AS VALUE --> 
<!-- mssql:select @@IDENTITY as value --> 
<!-- oracle:SELECT STOCKIDSEQUENCE.NEXTVAL AS VALUE FROM DUAL --> 
<!-- 还有一点需要注意的是不同的数据库生产商生成主键的方式不一样,有些是预先生成 (pre-generate)主键的,如Oracle和PostgreSQL。 
40.有些是事后生成(post-generate)主键的,如MySQL和SQL Server 所以如果是Oracle数据库,则需要将selectKey写在insert之前 --> 
 
 </selectKey>
 </insert>
  
<delete id="deleteStudentById" parameterClass="int">
<!-- #id#里的id可以随意取,但是上面的insert则会有影响,因为上面的name会从Student里的属性里去查找 --> 
<!-- 我们也可以这样理解,如果有#占位符,则ibatis会调用parameterClass里的属性去赋值 --> 
 delete from student where id=#id#
</delete>

<update id="updateStudent" parameterClass="Student">
 update Student set name=#name#,birth=#birth#,score=#score# where id=#id#
</update>
  
</sqlMap>


 

 5.编写总配置文件 :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>
<!-- 引用 JDBC属性的配置文件  -->
  <properties resource="com/zeng/entity/SqlMap.properties"/>
  
  <!-- 使用JDBC的事务的管理  -->
  <transactionManager type="JDBC">
   <!-- 配置数据源 -->
   <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>
  <sqlMap resource="com/zeng/entity/Student.xml"/>
  
</sqlMapConfig>


 

 6.创建业务层接口:StudentDaoImp.java

 

package com.zeng.dao;

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.zeng.entity.Student;

public class StudentDaoImp implements StudentDao {

	private static SqlMapClient sqlmapclient = null;
	
	static{
		try {
			Reader reader = Resources.getResourceAsReader("com/zeng/entity/SqlMapConfig.xml");
			sqlmapclient = SqlMapClientBuilder.buildSqlMapClient(reader); 
			reader.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	@Override
	public boolean addStudent(Student student) {
		// TODO Auto-generated method stub
		Object obj = null;
		try {
			obj = sqlmapclient.insert("addStudent",student);
			System.out.println("添加学生信息的返回值 :"+obj);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return obj!=null;
	}

	@Override
	public boolean deleteStudentById(int id) {
		// TODO Auto-generated method stub
		Object obj = null;
		try {
			obj=sqlmapclient.delete("deleteStudentById",id);
			System.out.println("删除学生的返回值:"+obj+",这里的返回值是受影响的行数 !");
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return obj!=null;
	}

	@Override
	public List<Student> selectAllStudent() {
		// TODO Auto-generated method stub
		try {
			return sqlmapclient.queryForList("selectAllStudent");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public List<Student> selectAllStudentByName(String name) {
		// TODO Auto-generated method stub
		try {
			return sqlmapclient.queryForList("selectStudentByName",name);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Student selectStudentById(int id) {
		// TODO Auto-generated method stub
		
		try {
			return (Student) sqlmapclient.queryForObject("selectStudentById",id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public boolean updateStudent(Student student) {
		// TODO Auto-generated method stub
		
		Object obj = null;
		try {
			obj=sqlmapclient.update("updateStudent", student);
			System.out.println("更新学生的返回值:"+obj+",返回值受影响行数 !");
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return obj!=null;
	}

}


 

7.创建接口实现类:StudentDao.java

 

package com.zeng.dao;

import java.util.List;

import com.zeng.entity.Student;

public interface StudentDao {
	
	/**
	 * 增加学生
	 * @param student 学生实体类
	 * @return  返回添加是否成功 
	 */
	boolean addStudent(Student student);
	
	/**
	 * 根据ID删除学生
	 * @param id  学生ID
	 * @return	返回删除是否成功 
	 */
	boolean deleteStudentById(int id);
	
	/**
	 * 更新学生信息
	 * @param student 学生对象
	 * @return	返回更新是否成功 
	 */
	boolean updateStudent(Student student);
	
	/**
	 * 查询所有的学生信息
	 * @return 返回学生列表
	 */
	List<Student> selectAllStudent();
	
	/**
	 * 根据学生姓名模糊查询学生信息
	 * @param name 学生姓名
	 * @return	返回学生列表
	 */
	List<Student> selectAllStudentByName(String name);
	
	/**
	 * 根据学生ID查询学生信息
	 * @param id  学生ID
	 * @return	  返回学生对象
	 */
	Student selectStudentById(int id);

}


 

8.创建测试类:TestIbatis.java

 

package com.zeng.view;

import java.sql.Date;
import java.util.List;

import com.zeng.dao.StudentDao;
import com.zeng.dao.StudentDaoImp;
import com.zeng.entity.Student;

public class TestIbatis {

	public static void main(String[] args) {
		StudentDao studentDaoImpl = new StudentDaoImp();
		
		System.out.println("测试插入"); 
		Student addStudent = new Student(); 
		addStudent.setName("李四"); 
		addStudent.setBirth(Date.valueOf("2011-09-02")); 
		addStudent.setScore(88); 
		System.out.println(studentDaoImpl.addStudent(addStudent)); 
         
		
		System.out.println("测试根据id查询"); 
		System.out.println(studentDaoImpl.selectStudentById(1)); 
		System.out.println("测试模糊查询"); 
		List<Student> mohuLists = studentDaoImpl.selectAllStudentByName("李"); 
		if(mohuLists!=null){
			for (Student student : mohuLists) { 
			System.out.println(student); 
			} 
		}
		
		System.out.println("测试查询所有"); 
		List<Student> students = studentDaoImpl.selectAllStudent(); 
		for (Student student : students) { 
		System.out.println(student); 
		} 
		
		System.out.println("根据id删除学生信息"); 
		System.out.println(studentDaoImpl.deleteStudentById(1)); 
		
		System.out.println("测试更新学生信息"); 
		Student updateStudent = new Student(); 
		updateStudent.setId(2); 
		updateStudent.setName("小胖"); 
		updateStudent.setBirth(Date.valueOf("2011-08-07")); 
		updateStudent.setScore(21); 
		System.out.println(studentDaoImpl.updateStudent(updateStudent)); 
}

}


 

iBatis 的优缺点:

优点:

1、 减少代码量,简单;

2、 性能增强;

3、 Sql 语句与程序代码分离;

4、 增强了移植性;

缺点:

1、 和Hibernate 相比,sql 需要自己写;

2、 参数数量只能有一个,多个参数时不太方便;

相关文章
相关标签/搜索