码迷,mamicode.com
首页 > 其他好文 > 详细

初学Ibatis

时间:2015-08-11 16:15:30      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:ibatis   orm   database   java   

    iBatis是一款使用方便的数据访问工具,也可作为数据持久层的框架。和ORM框架(如Hibernate)将数据库表直接映射为Java对象相比,iBatis是将SQL语句映射为Java对象。相对于全自动SQL的Hibernate,iBatis允许你对SQL有完全控制权,可以视为半自动的数据访问工具。 

    iBatis的最大优点是简便,轻量级,仅需iBatis的一个jar和数据库的驱动即可运行,而且使用iBatis仅需掌握SQL和XML的用法即可,而不像Hibernate那样需要配置对象间的关系。学习iBatis的过程要比Hibernate快很多,在项目中,若人员水平不大一致时,使用iBatis代替Hibernate作为数据访问工具可以有效提升开发效率。


现在我们来开始搭建ibatis环境:

1、导入包:ibatis-2.3.0.677.jar、mysql-connector-java-5.1.18-bin.jar

ibatis需要导入的包很少,只需要导入ibatis的包以及驱动包即可


2、建立model类,这里需要一个不带参数的默认构造函数,因为包括Hibernate在内的映射都是使用反射的,如果没有无参构造可能会出现问题

public class Student {
	private int id;
	private String name;
	private Date birth;
	private float score;

	public Student() {
	}
	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;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", birth=" + birth
				+ ", score=" + score + "]";
	}
}
对应的数据库表为:

技术分享

3、Student.xml,javabean的映射配置文件

<?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.entity.Student" />

	<!-- id表示select里的sql语句,resultClass表示返回结果的类型 -->
	<select id="selectAllStudent" resultClass="Student">
		select * from
		tbl_student
	</select>

	<!-- parameterClass表示参数的内容 -->
	<!-- #表示这是一个外部调用的需要传进的参数,可以理解为占位符 -->
	<select id="selectStudentById" parameterClass="int" resultClass="Student">
		select * from tbl_student where id=#id#
	</select>

	<!-- 注意这里的resultClass类型,使用Student类型取决于queryForList还是queryForObject -->
	<select id="selectStudentByName" parameterClass="String"
		resultClass="Student">
		select name,birth,score from tbl_student where name like
		'%$name$%'
	</select>
	<insert id="addStudent" parameterClass="Student">
		insert into
		tbl_student(name,birth,score) values
		(#name#,#birth#,#score#)
		<selectKey resultClass="int" keyProperty="id">
			SELECT
			LAST_INSERT_ID() 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。 
				有些是事后生成(post-generate)主键的,如MySQL和SQL Server 所以如果是Oracle数据库,则需要将selectKey写在insert之前 -->
		</selectKey>
	</insert>

	<!-- #id#里的id可以随意取,但是上面的insert则会有影响,因为上面的name会从Student里的属性里去查找 -->
	<delete id="deleteStudentById" parameterClass="int">
		delete from
		tbl_student where id=#id#
	</delete>
	<update id="updateStudent" parameterClass="Student">
		update tbl_student set
		name=#name#,birth=#birth#,score=#score# where id=#id#
	</update>
</sqlMap>


4、SqlMap.properties

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

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>
	<properties resource="SqlMap.properties" />
	<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="ibatisconfig/Student.xml" />
</sqlMapConfig>

6、编写DAO类

StudentDao接口:

public interface StudentDao {
	/**
	 * 添加学生信息
	 * 
	 * @param student
	 *            学生实体
	 * @return 返回是否添加成功
	 */
	public boolean addStudent(Student student);

	/**
	 * 根据学生id删除学生信息
	 * 
	 * @param id
	 *            学生id
	 * @return 删除是否成功
	 */
	public boolean deleteStudentById(int id);

	/**
	 * 更新学生信息
	 * 
	 * @param student
	 *            学生实体
	 * @return 更新是否成功
	 */
	public boolean updateStudent(Student student);

	/**
	 * 查询全部学生信息
	 * 
	 * @return 返回学生列表
	 */
	public List<Student> selectAllStudent();

	/**
	 * 根据学生姓名模糊查询学生信息
	 * 
	 * @param name
	 *            学生姓名
	 * @return 学生信息列表
	 */
	public List<Student> selectStudentByName(String name);

	/**
	 * 根据学生id查询学生信息
	 * 
	 * @param id
	 *            学生id
	 * @return 学生对象
	 */
	public Student selectStudentById(int id);
}
StudentDaoImpl实现类:

public class StudentDaoImpl implements StudentDao {
	private static SqlMapClient sqlMapClient = null;
	static {
		try {
			Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
			sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean addStudent(Student student) {
		Object ob = null;
		boolean flag = false;
		try {
			ob = sqlMapClient.insert("addStudent", student);
			System.out.println("添加学生信息的返回值:" + ob);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (ob != null) {
			flag = true;
		}
		return flag;
	}

	@Override
	public boolean deleteStudentById(int id) {
		Object ob = null;
		boolean flag = false;
		try {
			ob = sqlMapClient.delete("deleteStudentById", id);
			System.out.println("删除学生信息的返回值:" + ob + ",这里返回的是影响的行数");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (ob != null) {
			flag = true;
		}
		return flag;
	}

	@Override
	public boolean updateStudent(Student student) {
		boolean flag = false;
		Object object = false;
		try {
			object = sqlMapClient.update("updateStudent", student);
			System.out.println("更新学生信息的返回值:" + object + ",返回影响的行数");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (object != null) {
			flag = true;
		}
		return flag;
	}

	@Override
	public List<Student> selectAllStudent() {
		List<Student> students = null;
		try {
			students = sqlMapClient.queryForList("selectAllStudent");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return students;
	}

	@Override
	public List<Student> selectStudentByName(String name) {
		List<Student> students = null;
		try {
			students = sqlMapClient.queryForList("selectStudentByName", name);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return students;
	}

	@Override
	public Student selectStudentById(int id) {
		Student student = null;
		try {
			student = (Student) sqlMapClient.queryForObject(
					"selectStudentById", id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return student;
	}
}

7、测试

public class TestIbatis {
	public static void main(String[] args) {
		StudentDaoImpl studentDaoImpl = new StudentDaoImpl();
		System.out.println("测试插入");
		Student addStudent = new Student();
		addStudent.setName("王五");
		addStudent.setBirth(Date.valueOf("2015-09-02"));
		addStudent.setScore(48);
		System.out.println(studentDaoImpl.addStudent(addStudent));
		System.out.println("测试根据id查询");
		System.out.println(studentDaoImpl.selectStudentById(1));
		System.out.println("测试模糊查询");
		List<Student> mohuLists = studentDaoImpl.selectStudentByName("李");
		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(6);
		updateStudent.setName("李四1");
		updateStudent.setBirth(Date.valueOf("2011-08-07"));
		updateStudent.setScore(21);
		System.out.println(studentDaoImpl.updateStudent(updateStudent));
	}
}
控制台信息为:

技术分享
成功运行!


项目结构为:

技术分享



版权声明:本文为博主原创文章,未经博主允许不得转载。

初学Ibatis

标签:ibatis   orm   database   java   

原文地址:http://blog.csdn.net/kevinxxw/article/details/47420331

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!