ibatis 轻松入门

1、总中的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig> <transactionManager type="JDBC"> <!-- 定义了ibatis的事务管理器有3中(JDBC,JTA,EXTERNAL) -->
<dataSource type="SIMPLE"> <!-- type属性指定了数据源的链接类型,也有3种类型(SIMPLE,DBCP,JNDI) -->
<property name="JDBC.Driver" value="com.mysql.jdbc.Driver" />
<property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost/ibatis" />
<property name="JDBC.Username" value="root" />
<property name="JDBC.Password" value="123" /> </dataSource>
</transactionManager>
<sqlMap resource="com/huwei/model/Student.xml" />
</sqlMapConfig>

2、映射文件,ibatis 可以将sql语句写在配置文件中

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap
PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-2.dtd">
<sqlMap>
<typeAlias alias="Student" type="com.huwei.model.Student" />
<select id="selectAllStudent" resultClass="Student">
select * from student
</select>
<select id="selectById" parameterClass="int" resultClass="Student">
select * from student where id=#id#
</select>
<insert id="insertStudent" parameterClass="Student">
insert into Student(name,major)
values (#name#,#major#)
</insert>
<delete id="deleteStudentById" parameterClass="int">
delete from Student where id=#id#
</delete>
</sqlMap>

3、实体类

public class Student {
private int id;
private String name;//名字
private String major;//专业
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 getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
@Override
public String toString() {
return "name="+name+" id="+id+" major="+ major;
} }

4、几个主要的dao层方法

public void deleteStudentById(int id) {//根据id删除学生
try {
sqlMapClient.delete("deleteStudentById",id);
} catch (SQLException e) {
e.printStackTrace();
} } @Override
public void addStudent(Student student) {//添加学生
try {
sqlMapClient.insert("insertStudent",student);
} catch (SQLException e) {
e.printStackTrace();
} }

5、目录结构如下

ibatis 轻松入门

6、ibatis总结

个人觉得相比于hibernate,ibatis更加容易上手

上一篇:高仿Readhub小程序 微信小程序项目【原】


下一篇:C标准I/O建立一个文件仓库