Spring + Ibatis + MySql+Java實例詳解

 

將以下jar包加入到工程,commons-logging-1.0.4.jar、ibatis-2.3.0.677.jar、mysql-connector-java-5.0.3-bin.jar、spring.jar。

 



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>
	<sqlMap resource="spring/beans/student.xml"/>
</sqlMapConfig>


sqlMapClient.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
	    <property name="url" value="jdbc:mysql://localhost:3306/test"/>
	    <property name="username" value="root"/>
	    <property name="password" value="root"/>
	  </bean>
    
    <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
  		<property name="configLocation">
    		<value>spring/beans/sqlMapConfig.xml</value>
  		</property>
  		<property name="dataSource">
    		<ref bean="dataSource"/>
  		</property>
	</bean>
    
	<bean id="studentDao" class="spring.dao.StudentDaoImpl">
  		<property name="sqlMapClient">
    		<ref bean="sqlMapClient"/>
  		</property>
	</bean>
	
</beans>


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="spring.beans.Student"/>
	
	<resultMap id="studentMap" class="spring.beans.Student">
		<result property="id" column="id"/>
		<result property="name" column="name"/>
		<result property="psw" column="psw"/>
		<result property="enabled" column="enabled"/>
	</resultMap>
	
	<insert id="addStudent" parameterClass="student">
		insert into student (name,psw,enabled) values(#name#,#psw#,#enabled#);
		<selectKey resultClass="int" keyProperty="id">
             select @@identity as inserted
        </selectKey>
	</insert>
	<select id="queryStudentByName" parameterClass="string" resultMap="studentMap">
		<![CDATA[
			SELECT * FROM student WHERE NAME=#name#
		]]>
	</select>
	
	<select id="queryAllStudent" resultMap="studentMap">
		<![CDATA[
			SELECT * FROM student
		]]>
	</select>
	 <update id="updateStudent" parameterClass="student">
         update student set id=#id#,psw=#psw#,enabled=#enabled# where id=#id#
     </update>
     <delete id="deleteStudentById" parameterClass="int">
         delete from student where id=#id#
     </delete>
</sqlMap>


Student.java

package spring.beans;

import java.io.Serializable;

public class Student implements Serializable {

	private static final long serialVersionUID = 1L;

	private int id;
	private String name;
	private String psw;
	private Boolean enabled;

	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 String getPsw() {
		return psw;
	}

	public void setPsw(String psw) {
		this.psw = psw;
	}

	public Boolean getEnabled() {
		return enabled;
	}

	public void setEnabled(Boolean enabled) {
		this.enabled = enabled;
	}

	@Override
	public String toString() {
		return "id=" + id + "\t 姓名=" + name + "\t 密碼=" + psw + "\t 是否註冊="
				+ enabled + "\n";
	}
}

 

StudentDao.java

package spring.dao;

import java.util.List;
import spring.beans.Student;

public interface StudentDao {
	/*
	 * 添加學生信息
	 */
	public boolean addStudent(Student student);

	/*
	 * 根據id刪除學生信息
	 */
	public boolean deleteStudentById(int id);

	/*
	 * 更新學生信息
	 */
	public boolean updateStudent(Student student);

	/*
	 * 查詢全部學生信息
	 */
	public List<Student> selectAllStudent();

	/*
	 * 根據學生姓名模糊查詢學生信息
	 */
	public List<Student> selectStudentByName(String name);

	/*
	 * 根據學生id查詢學生信息
	 */
	public Student selectStudentById(int id);
}


StudentDaoImpl.java

package spring.dao;

import java.util.List;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import spring.beans.Student;

public class StudentDaoImpl extends SqlMapClientDaoSupport implements StudentDao {
	public boolean addStudent(Student student) {
		Object object = null;
		boolean flag = false;
		try {
			object=getSqlMapClientTemplate().insert("addStudent", student);
			//System.out.println("添加學生信息的返回值:" + object);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (object != null) {
			flag = true;
		}
		return flag;
	}

		public boolean deleteStudentById(int id) {
		Object object = null;
		boolean flag = false;
		try {
			object =getSqlMapClientTemplate().delete("deleteStudentById",id);
			// System.out.println("刪除學生信息的返回值:" + object + ",這裏返回的是影響的函數");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (object != null) {
			flag = true;
		}
		return flag;
	}

	public boolean updateStudent(Student student) {
		Object object = null;
		boolean flag = false;
		try {
		object= getSqlMapClientTemplate().update("updateStudent", student);
			// System.out.println("更新學生信息的返回值:" + object );
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (object != null) {
			flag = true;
		}
		return flag;
	}

	public List<Student> selectAllStudent() {
		List<Student> students = null;
		try {
			students = getSqlMapClientTemplate().queryForList("queryAllStudent",null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return students;
	}

	public List<Student> selectStudentByName(String name) {
		List<Student> students = null;
		try{
			students=getSqlMapClientTemplate().queryForList("queryStudentByName", name);
		} catch(Exception e) {
			e.printStackTrace();
		}
		return students;
	}

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


TestStudent.java

package spring.beans;

import spring.beans.Student;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import spring.dao.StudentDao;

public class TestStudent {
	public static void main(String[] args) {

		//初始化beans.xml文件
		ApplicationContext ctx = new ClassPathXmlApplicationContext("spring/beans/sqlMapClient.xml");
		StudentDao studentDao = (StudentDao)ctx.getBean("studentDao");
		
		// 查詢所有
		System.out.println("查詢初始數據表:");
		List<Student> list1 = studentDao.selectAllStudent();
		for (Student student : list1) {
			System.out.println(student);
		}
		
		// 測試插入
		System.out.println("測試插入:");
		Student addStudent = new Student();
		//addStudent.setId(2);
		addStudent.setName("Tom");
		addStudent.setPsw("Tompsw");
		addStudent.setEnabled(false);
		System.out.println(studentDao.addStudent(addStudent));

		//addStudent.setId(7);
		addStudent.setName("John");
		addStudent.setPsw("Johnpsw");
		addStudent.setEnabled(true);
		System.out.println(studentDao.addStudent(addStudent));
		
		// 查詢所有
		System.out.println("查詢修改後數據表:");
		List<Student> list2 = studentDao.selectAllStudent();
		for (Student student : list2) {
			System.out.println(student);
		}		
				
		// 根據姓名查詢
		System.out.println("根據姓名查詢:");
		List<Student> list = studentDao.selectStudentByName("John");
		for (Student student : list) {
			System.out.println(student);
		}
		
		// 更新信息
		System.out.println("更新信息:");
		Student updateStudent = new Student();
		addStudent.setId(2);
	    updateStudent.setName("Lucy");
		updateStudent.setPsw("lucypsw");
		updateStudent.setEnabled(true);
		System.out.println(studentDao.updateStudent(updateStudent));
		
		// 查詢所有
		System.out.println("查詢修改後數據表:");
		List<Student> list3 = studentDao.selectAllStudent();
		for (Student student : list3) {
			System.out.println(student);
		}
		
		// 刪除數據
		System.out.println("刪除數據:");
		System.out.println(studentDao.deleteStudentById(2));
		
		// 查詢所有
		System.out.println("查詢修改後數據表:");
		List<Student> list4 = studentDao.selectAllStudent();
		for (Student student : list4) {
			System.out.println(student);
		}
	}

}


 

轉載:http://blog.csdn.net/lanpiao_87/article/details/7036409
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章