真不好意识,前不久写了篇iBATIS入门,由于那时候快过年了,一直没有心情写,现在上班了,也没什么事情做,就在这里继续写写吧,O(∩_∩)O哈哈~,希望各位能够喜欢。
首先我们需要下载一些iBATIS的jar包,这个我就不在这里说了,网上有,我是用的ibatis-2.3.0.677.jar
数据库是用的Oracle9i,开发工具是MyEclipse;
数据库脚本
create table student(
sid integer not null primary key,
sname nvarchar2 (50),
major nvarchar2 (50),
score float ,
birth date
);
首先我们需要在src目录下创建个SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"">
<sqlMapConfig>
<!--
假如我们需要引入额外的文件就是这样引用的
<providers embedded="resources.providers.config, IBatisNet.Test"/>
-->
<!-- Configure a built-in transaction manager. If you're using an
app server, you probably want to use its transaction manager
and a managed datasource -->
<!-- 配置事物,以及数据库的链接属性 -->
<settings
cacheModelsEnabled="true"
enhancementEnabled="true"
lazyLoadingEnabled="true"
maxRequests="32"
maxSessions="10"
maxTransactions="5"
useStatementNamespaces="false"
/>
<transactionManager type="JDBC" commitRequired="false">
<dataSource type="SIMPLE">
<!-- sql2000的配置 -->
<!-- <property name="JDBC.Driver" value="net.sourceforge.jtds.jdbc.Driver"/>
<property name="JDBC.ConnectionURL" value="jdbc:jtds:sqlserver://localhost:1433;DataBaseName=MyTest"/>
<property name="JDBC.Username" value="sa"/>
<property name="JDBC.Password" value=""/> -->
<property name="JDBC.Driver" value="oracle.jdbc.driver.OracleDriver"/>
<property name="JDBC.ConnectionURL" value="jdbc:oracle:thin:@localhost:1521:oracle9i"/>
<property name="JDBC.Username" value="scott"/>
<property name="JDBC.Password" value="tiger"/>
</dataSource>
</transactionManager>
<!-- List the SQL Map XML files. They can be loaded from the
classpath, as they are here (com.domain.data...) -->
<!-- 此处是用来配置相对应的bean对应的配置文件,以及sql语句 -->
<sqlMap resource="com/ibats/bean/Student.xml"/>
</sqlMapConfig>
bean我就不在这里写了,各位自己写下
然后我在这里关键是讲解下Student.xml 下面怎样整合sql语句
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"">
<sqlMap namespace="Student">
<!-- 为这个类起个别名 -->
<typeAlias alias="Student" type="com.ibats.bean.Student" />
<!-- 查询所有 -->
<select id="selectAllStudent" resultClass="Student">
select * from student order by sid
</select>
<!--指定条件查询 -->
<select id="selectStudentById" parameterClass="int"
resultClass="Student">
select * from student where sid = #sid#
</select>
<select id="selectStudentCount" resultClass="Integer">
select count(1) from student
</select>
<!-- 模糊查询-->
<select id="selectStudentByName" parameterClass="String"
resultClass="Student">
select sid,sname,major,score,birth from Student where sname like
'%$sname$%'
</select>
<!-- 动态查询 -->
<select id="selectByDynamic" resultClass="Student">
select * from student
<dynamic prepend="where">
<isNotEmpty property="major">major = #major#</isNotEmpty>
</dynamic>
</select>
<select id="selectByGreate" resultClass="Student">
select * from student
<!-- 当sid>1013时执行下面操作 -->
<isGreaterThan property="sid" compareValue="1013">
where sid > #sid#
</isGreaterThan>
order by sid
</select>
<!-- 判断sname属性是否为null,score属性是否为null,并且sid 大于1119 -->
<select id="DynamicStudent" resultClass="Student">
select * from student
<dynamic prepend="where">
<isNotNull prepend="and" property="sname">
(sname = #sname#
<isNotNull prepend="or" property="score">
score = #score#
</isNotNull>
)
</isNotNull>
<isNotNull prepend = "and" property = "major">
major = #major#
</isNotNull>
<isGreaterThan prepend ="and" property = "sid" compareValue = "1119">
sid > 1119
</isGreaterThan>
</dynamic>
</select>
<!-- 对数据进行排序sortvalue我们是已经在student中定义好的属性 -->
<statement id="getOrderStu" resultClass = "Student">
select * from student
<dynamic prepend = "order by">
<isNotEmpty property = "sortvalue">
sid $sortvalue$
</isNotEmpty>
</dynamic>
</statement>
<!-- 模糊查询 -->
<select id="blurStudent" resultClass = "student">
select * from student
<dynamic prepend = "where">
<isNotEmpty property = "major">
major like '%$major$%'
</isNotEmpty>
</dynamic>
</select>
<!-- 插入语句 -->
<insert id="insertStudent" parameterClass="student">
insert into Student(sid,sname,major,birth,score) values
(#sid#,#sname#,#major#,#birth#,#score#)
</insert>
<!-- 删除语法 -->
<delete id="deleteStudentById" parameterClass="int">
delete from Student where sid = #sid#
</delete>
<!-- 修改语句-->
<update id="updateStudent" parameterClass="student">
update Student set sname =#sname# , major = #major#, score =
#score#, birth = #birth# where sid = #sid#
</update>
<!-- 我们可以在statement里面进行insert,update,select操作 -->
<statement id="insertStateStu" parameterClass="student">
insert into Student (sid,sname,major,birth,score) values
(#sid#,#sname#,#major#,#birth#,#score#)
</statement>
<!-- 插入时自动生成主键 -->
<!-- 针对Oracle我们首先需要创建其序列
create sequence workRecord_ID minvalue 1000 maxvalue 99999999 start with 1000 increment by 1 nocache;
-->
<insert id="insertStuSeque" parameterClass="student">
<selectKey resultClass="int" type="pre" keyProperty="sid">
SELECT scott.workRecord_ID.nextval AS sid FROM dual
</selectKey>
insert into student(sid,sname,major,birth,score) values
(#sid#,#sname#,#major#,#birth#,#score#)
</insert>
</sqlMap>
我想注释已近非常详细了,然后就是我们的接口了
package com.ibats.dao;
import java.util.List;
import com.ibats.bean.Student;
public interface StudentDAO {
public void addStudent(Student student);
public void addStudentBySeuque(Student student);
public void deleteStduent(int sid);
public void updateStudent(Student student);
public List<Student> queryAllStudent();
public Student queryStudentById(int id);
public Student queryStudentByName(String name);
public List<Student> queryDynamic(Student student) ;
public void addStudentBystat(Student student);
public int getAllCount();
}
剩下来就是我们的实现类了
package com.ibats.dao.imp;
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;
import com.ibats.bean.Student;
import com.ibats.dao.StudentDAO;
public class IStudentDaoImp implements StudentDAO {
public Student queryStudentByName(String name) {
List<Student> stuList = null;
try {
stuList = sqlMapClient.queryForList("selectStudentByName", name);
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println(stuList.size());
return stuList.get(0);
}
private static SqlMapClient sqlMapClient = null;
static {
try {
Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
public void addStudent(Student student) {
try {
sqlMapClient.insert("insertStudent", student);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void addStudentBySeuque(Student student) {
try {
sqlMapClient.insert("insertStuSeque", student);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void deleteStduent(int sid) {
try {
System.out.println(sqlMapClient.delete("deleteStudentById", sid));
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<Student> queryAllStudent() {
try {
List<Student> stuData = sqlMapClient
.queryForList("selectAllStudent");
System.out.println(stuData.size());
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public Student queryStudentById(int id) {
try {
Student stu = (Student) sqlMapClient.queryForObject(
"selectStudentById", id);
if (null != stu)
System.out.println(stu.getMajor());
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public void updateStudent(Student student) {
try {
System.out.println(sqlMapClient.update("updateStudent", student));
} catch (SQLException e) {
e.printStackTrace();
}
}
public void queryLikeStu() {
Student st = new Student();
st.setMajor("软件开发");
try {
sqlMapClient.queryForList("blurStudent", st);
} catch (SQLException e) {
e.printStackTrace();
}
}
//分页查询
public void queryPageStu() {
try {
sqlMapClient.queryForList("selectAllStudent", null, 3, 5);
} catch (Exception e) {
}
}
public static void main(String args[]) {
StudentDAO sdao = new IStudentDaoImp();
IStudentDaoImp sdi = new IStudentDaoImp();
sdi.queryPageStu();
//sdi.queryLikeStu();
// sdi.queryOrder();
// sdi.queryByDanmic();
// sdao.queryAllStudent();
// sdao.queryStudentById(1);
/*
* Student st = new Student(); st.setSid(1219); st.setBirth(new Date(new
* java.util.Date().getTime())); st.setMajor("软件开发ab"); st.setScore(56);
* st.setSname("tempuslibin"); sdao.addStudent(st);
*/
// sdao.deleteStduent(10);
/*
* Student st = new Student(); st.setSid(1029); st.setBirth(new Date(new
* java.util.Date().getTime())); st.setMajor("体验生活"); st.setScore(560);
* st.setSname("libins"); sdao.updateStudent(st);
*/
// sdao.queryStudentByName("l");
/*
* Student stu = new Student(); stu.setSname("软件开发");
* stu.setMajor("软件开发"); stu.setScore(56); sdao.queryDynamic(stu);
*/
/*
* Student st = new Student(); st.setSid(12191); st.setBirth(new
* Date(new java.util.Date().getTime())); st.setMajor("软件开发ab");
* st.setScore(56); st.setSname("tempuslibin");
* sdao.addStudentBystat(st);
*/
// sdao.getAllCount();
/*
* Student st = new Student(); st.setBirth(new Date(new
* java.util.Date().getTime())); st.setMajor("软件开发ab"); st.setScore(56);
* st.setSname("tempuslibin"); sdao.addStudentBySeuque(st);
*/
}
public void queryOrder() {
Student st = new Student();
st.setSortvalue(" desc");
try {
this.sqlMapClient.queryForList("getOrderStu", st);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void queryByDanmic() {
Student st = new Student();
st.setMajor("软件开发ab");
// st.setScore(56);
st.setSname("tempuslibin");
st.setSid(1129);
try {
this.sqlMapClient.flushDataCache();
this.sqlMapClient.queryForList("DynamicStudent", st);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void queryByGreat() {
Student st = new Student();
st.setSid(1029);
try {
sqlMapClient.queryForList("selectByGreate", st);
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<Student> queryDynamic(Student student) {
try {
List<Student> data = sqlMapClient.queryForList("selectByDynamic",
student);
print(data);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public void print(List<Student> data) {
int size = data.size();
Student stu = null;
for (int i = 0; i < size; i++) {
stu = data.get(i);
System.out.println(stu.getSid() + " " + stu.getSname() + " "
+ stu.getScore() + " " + stu.getBirth());
}
}
public void print(Object o) {
// System.out.
}
public void addStudentBystat(Student student) {
try {
sqlMapClient.insert("insertStateStu", student);
} catch (SQLException e) {
e.printStackTrace();
}
}
public int getAllCount() {
try {
int count = (Integer) sqlMapClient
.queryForObject("selectStudentCount");
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
}
大家可以进行下学习,确实iBATIS是个不错的关于dao层的操作,值得我们去研究,我想大家通过今天的研究对单个表的操作已近非常熟悉了吧。
如果以后有时间我会写下关于多个表的操作,谢谢大家的关注,如有什么疑问和需要帮助之处,请留言。谢谢