测试项目目录结构如图所示
SqlMap.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test username=root password=123456
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/ibatis/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/ibatis/Student.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使得我们在下面使用Student实体类的时候不需要写包名 --> <typeAlias alias="Student" type="com.ibatis.Student" /> <!-- 这样以后改了sql,就不需要去改java代码了 --> <!-- id表示select里的sql语句,resultClass表示返回结果的类型 --> <select id="selectAllStudent" resultClass="Student"> select * from t_student </select> <!-- parameterClass表示参数的内容 --> <!-- #表示这是一个外部调用的需要传进的参数,可以理解为占位符 --> <select id="selectStudentById" parameterClass="int" resultClass="Student"> select * from t_student where id=#id# </select> <!-- 注意这里的resultClass类型,使用Student类型取决于queryForList还是queryForObject --> <select id="selectStudentByName" parameterClass="String" resultClass="Student"> select id,name,birth,score from t_student where name like '%$name$%' </select> <insert id="addStudent" parameterClass="Student"> insert into t_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。 有些是事后生成(post-generate)主键的,如MySQL和SQL Server 所以如果是Oracle数据库,则需要将selectKey写在insert之前 --> </selectKey> </insert> <delete id="deleteStudentById" parameterClass="int"> <!-- #id#里的id可以随意取,但是上面的insert则会有影响,因为上面的name会从Student里的属性里去查找 --> <!-- 我们也可以这样理解,如果有#占位符,则ibatis会调用parameterClass里的属性去赋值 --> delete from t_student where id=#id# </delete> <update id="updateStudent" parameterClass="Student"> update t_student set name=#name#,birth=#birth#,score=#score# where id=#id# </update> </sqlMap>
实体类 Student.java
public class Student { private int id; private String name; private Date birth; private float score; //省略getter setter 和构造函数(有参和无参) }
Dao接口 StudentDao.java
package com.ibatis; import java.util.List; 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); }
Dao接口实现 StudentDaoImpl.java
package com.ibatis; 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; public class StudentDaoImpl implements StudentDao { private static SqlMapClient sqlMapClient = null; // 读取配置文件 static { try { Reader reader = Resources .getResourceAsReader("com/ibatis/SqlMapConfig.xml"); sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader); reader.close(); } catch (IOException e) { e.printStackTrace(); } } @Override public boolean addStudent(Student student) { Object object = null; boolean flag = false; try { object = sqlMapClient.insert("addStudent", student); System.out.println("添加学生信息的返回值:" + object); } catch (SQLException e) { e.printStackTrace(); } if (object != null) { flag = true; } return flag; } @Override public boolean deleteStudentById(int id) { boolean flag = false; Object object = null; try { object = sqlMapClient.delete("deleteStudentById", id); System.out.println("删除学生信息的返回值:" + object + ",这里返回的是影响的行数"); } catch (SQLException e) { e.printStackTrace(); } if (object != 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; } }
测试类 Main.java
public class Main { public static void main(String[] args) { //添加学生信息 StudentDao studentDao = new StudentDaoImpl(); Student student = new Student(); student.setName("admin"); student.setBirth(new Date(System.currentTimeMillis())); student.setScore(85); System.out.println(studentDao.addStudent(student)); // 根据id查询 System.out.println(studentDao.selectStudentById(1)); // 模糊查询 List<Student> lists = studentDao.selectStudentByName("a"); for (Student s : lists) { System.out.println(s); } // 查询所有 List<Student> students = studentDao.selectAllStudent(); for (Student s : students) { System.out.println(s); } //根据id删除学生信息 System.out.println(studentDao.deleteStudentById(1)); //更新学生信息 Student updateStudent = new Student(); updateStudent.setId(1); updateStudent.setName("李四1"); updateStudent.setBirth(Date.valueOf("2011-08-07")); updateStudent.setScore(21); System.out.println(studentDao.updateStudent(updateStudent)); } }
数据库为test,表名student
基本的CURD在这里的,实际项目中可能会结合Spring使用,到时候看着办吧~~~
2015年7月12日21:16:59