日期:2014-05-16 浏览次数:20743 次
<?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">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="com.mysql.jdbc.Driver" />
<property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost:3306/ibatis" />
<property name="JDBC.Username" value="root" />
<property name="JDBC.Password" value="123456" />
</dataSource>
</transactionManager>
<sqlMap resource="com/lamp/Student.xml" /> <!-- 映射文件 -->
</sqlMapConfig>
<?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>
<!--
<resultMap id="Student" class="com.lamp.Student">
<result property="sid" column="sid" />
<result property="sname" column="sname" />
<result property="major" column="major" />
<result property="birth" column="birth" />
</resultMap>
用了typeAlias就可以省略这些配置,javaBean的属性如上,并与数据库表student一一对应
-->
<typeAlias alias="Student" type="com.lamp.Student"/>
<!--查询所有学生-->
<select id="selectAllStudent" resultClass="Student">
select * from student
</select>
<!--根据id查询学生-->
<select id="selectStudentById" resultClass="Student" parameterClass="int">
select *
from student
where sid=#sid#
</select>
<!--插入学生记录-->
<insert id="insertStudent" parameterClass="Student">
insert into student (sid,sname,major,birth)
values (#sid#,#sname#,#major#,#birth#)
</insert>
<!--根据sid删除学生记录-->
<delete id="deleteStudentById" parameterClass="int">
delete
from student
where sid=#sid#
</delete>
<!--根据sid更新学生记录学生-->
<update id="updateStudentById" parameterClass="Student">
update student
set sid=#sid#,
sname=#sname#,
major=#major#,
birth=#birth#
where sid=#sid#
</update>
<!--根据学是姓名模糊查询-->
<select id="selectStudentByName" parameterClass="String" resultClass="Student">
select *
from student
where sname like '%$sname$%'
</select>
<!--主键生成方式,因为Mysql不支持创建序列,但是我们可以指定sid为int类型并将其设置为auto_increment也亦可-->
<insert id="insertStudentBySquence" parameterClass="Student">
<selectKey resultClass="int" keyProperty="sid">
select @@IDENTITY as sid
</selectKey>
insert into student (sid,sname,major,birth)
values(#sid#,#sname#,#major#,#birth#)
</insert>
</sqlMap>
private static SqlMapClient sqlMap = null;
//加载配置文件
static{
try {
Reader reader = Resources.getResourceAsReader("com/lamp/SqlMapConfig.xml");
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//方法如下
public List<Student> queryAllStudent() {
List<Student> studentList = null;
try {
studentList = sqlMap.queryForList("selectAllStudent");
} catch (SQLException e) {
e.printStackTrace();
}
return studentList;
}