一考润、簡述
?MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code刽沾,并且改名為MyBatis,實質上Mybatis對ibatis進行一些改進峭跳。 現(xiàn)在托管到gitHub上,下載:https://github.com/mybatis/mybatis-3/releases
MyBatis是一個優(yōu)秀的持久層框架膘婶,它對jdbc的操作數(shù)據(jù)庫的過程進行封裝,使開發(fā)者只需要關注 SQL 本身蛀醉,而不需要花費精力去處理例如注冊驅動悬襟、創(chuàng)建connection、創(chuàng)建statement拯刁、手動設置參數(shù)脊岳、結果集檢索等jdbc繁雜的過程代碼。
?這個demo是針對mybatis學習而進行的簡單的crud操作垛玻,并通過jsonp跨域將查詢封裝的數(shù)據(jù)發(fā)送至前臺割捅。關于mybatis這個框架的原理我就不再贅述了,上實例帚桩!
二亿驾、運行環(huán)境
2.1 軟件環(huán)境
Eclipse + Tomcat7 + Mysql
2.2 軟件架構
servlet+ mybatis框架 + html + bootstrap框架 + ajax + jsonp
2.3 數(shù)據(jù)庫表結構
CREATE TABLE `stu` (
`sno` varchar(10) NOT NULL,
`sname` varchar(20) NOT NULL,
`sage` int(10) DEFAULT NULL,
`ssex` varchar(5) DEFAULT NULL,
PRIMARY KEY (`sno`),
UNIQUE KEY `sno` (`sno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
2.4 主要jar包
三、例子結構
3.1 web項目結構
3.2 前臺項目結構
四账嚎、主要實現(xiàn)代碼
4.1 mybatis.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置通用mapper -->
<!-- <plugins></plugins> -->
<!-- 給路徑取別名,放在environments前面 -->
<!-- <typeAliases>
<typeAlias type="dao.StudentDao" alias="stu" />
</typeAliases> -->
<environments default="development">
<environment id="development">
<!-- 事務管理 -->
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="username" value="root" />
<property name="url" value="jdbc:mysql://localhost:3306/student" />
<property name="password" value="123" />
<property name="driver" value="com.mysql.jdbc.Driver" />
</dataSource>
</environment>
</environments>
<!-- 配置 映射文件 -->
<mappers>
<mapper resource="entity/StudentMapper.xml" />
</mappers>
</configuration>
4.2 StudentMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace命名空間,作用就是對sql進行分類管理
注意:使用mapper代理方法開發(fā)時,namespace需要特殊設置
-->
<mapper namespace="dao.StudentDao">
<!-- 查詢所有學生信息 -->
<resultMap type="entity.Student" id="stuMap">
<id column="sno" javaType="String" property="sno"></id>
<result column="sname" javaType="String" property="sname"/>
<result column="ssex" javaType="String" property="ssex"/>
<result column="sage" javaType="int" property="sage"/>
</resultMap>
<select id="findAllStudent" resultMap="stuMap">
select * from stu
</select>
<!-- 實現(xiàn)分頁查詢學生信息 -->
<select id="findPageStudent" parameterType="map" resultType="entity.Student">
SELECT * FROM stu LIMIT #{startSize},#{pageSize}
</select>
<!-- 實現(xiàn)學生信息的添加操作 -->
<insert id="doInsert" parameterType="entity.Student">
INSERT INTO stu
<include refid="columns_mysql"></include>
VALUES
<include refid="values_columns"></include>
</insert>
<!-- 添加的sql片段開始 -->
<sql id = "columns_mysql">
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="sno!=null">
sno,
</if>
<if test="sname!=null">
sname,
</if>
<if test="sage!=null">
sage,
</if>
<if test="ssex!=null">
ssex,
</if>
</trim>
</sql>
<sql id="values_columns">
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="sno!=null">
#{sno},
</if>
<if test="sname!=null">
#{sname},
</if>
<if test="sage!=null">
#{sage},
</if>
<if test="ssex!=null">
#{ssex},
</if>
</trim>
</sql>
<!-- 添加的sql片段結束 -->
<!-- 實現(xiàn)學生信息的更新操作 -->
<update id="doUpdateStudent" parameterType="entity.Student">
update stu
set sname = #{sname},
ssex = #{ssex},
sage = #{sage}
where sno = #{sno}
</update>
<!-- 根據(jù)學生id進行刪除操作 -->
<delete id="doDeleteBySno" parameterType="String">
delete from stu where sno = #{sno}
</delete>
<!-- 查詢學生表總人數(shù) -->
<select id="findCount" resultType="int">
select count(*) from stu
</select>
</mapper>
4.3 Mapper實現(xiàn)類StudentDaoImpl.java
public class StudentDaoImpl implements StudentDao {
private SqlSession sqlSession;
public List<Student> findAllStudent() {
sqlSession = SqlSessionUtil.getSession();
List<Student> list = sqlSession.selectList("findAllStudent");
sqlSession.commit();
sqlSession.close();
return list;
}
public List<Student> findPageStudent(Integer startSize, Integer pageSize) {
sqlSession = SqlSessionUtil.getSession();
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("startSize", startSize);
map.put("pageSize", pageSize);
List<Student> list = sqlSession.selectList("findPageStudent",map);
sqlSession.commit();
sqlSession.close();
return list;
}
public int doInsert(Student stu) {
sqlSession = SqlSessionUtil.getSession();
Integer result = sqlSession.insert("doInsert",stu);
sqlSession.commit();
sqlSession.close();
return result;
}
public int doDeleteBySno(String sno) {
sqlSession = SqlSessionUtil.getSession();
Integer result = sqlSession.delete("doDeleteBySno",sno);
sqlSession.commit();
sqlSession.close();
return result;
}
@Override
public int doUpdateStudent(Student stu) {
sqlSession = SqlSessionUtil.getSession();
Integer result = sqlSession.update("doUpdateStudent",stu);
sqlSession.commit();
sqlSession.close();
return result;
}
public int findCount() {
sqlSession = SqlSessionUtil.getSession();
Integer result = sqlSession.selectOne("findCount");
sqlSession.commit();
sqlSession.close();
return result;
}
}
4.4 StudentServiceImpl.java
private StudentDao stuDao = new StudentDaoImpl();
public List<Student> findAllStudent() {
return stuDao.findAllStudent();
}
public PageBean<Student> findPageStudent(Integer currentPage,
Integer pageSize) {
Integer count = stuDao.findCount();
Integer allPages = count/pageSize == 0 ? count/pageSize
: count/pageSize + 1;
if(currentPage > allPages){
currentPage = allPages;
}
if(currentPage < 1){
currentPage = 1;
}
PageBean<Student> pb = new PageBean<Student>();
Integer startSize = (currentPage-1)*pageSize;
List<Student> list = stuDao.findPageStudent(startSize, pageSize);
pb.setAllPages(allPages);
pb.setCount(count);
pb.setCurrentPage(currentPage);
pb.setCurrentCount(pageSize);
pb.setList(list);
return pb;
}
public int doInsert(Student stu) {
return stuDao.doInsert(stu);
}
public int doDeleteBySno(String sno) {
return stuDao.doDeleteBySno(sno);
}
public int doUpdateStudent(Student stu) {
return stuDao.doUpdateStudent(stu);
}
4.5 servlet主要操作的方法
4.5.1 分頁查詢方法
private void sendPageData(HttpServletRequest request,
HttpServletResponse response) throws IOException{
int pageSize = 5;
int currentPage = 1;
String currPage = request.getParameter("currentPage");
if(currPage!=null){
currentPage = Integer.parseInt(currPage);
}
PageBean<Student> pb = stuService.findPageStudent(currentPage, pageSize);
JSONObject json = JSONObject.fromObject(pb);
PrintWriter writer = response.getWriter();
String callback = request.getParameter("callback");
String result = callback + "(" + json.toString() + ")";
writer.write(result);
}
4.5.2 數(shù)據(jù)更新操作
private void doUpdate(HttpServletRequest request,
HttpServletResponse response) throws IOException{
String sno = request.getParameter("sno");
String sname = request.getParameter("sname");
String ssex = request.getParameter("ssex");
Integer sage = null;
if(request.getParameter("sage")!=null){
sage = Integer.parseInt(request.getParameter("sage"));
}
System.out.println("姓名:"+sname+"\t性別:"+ssex+"\t學號:"+sno+"\t年紀:"+sage);
Student stu = new Student();
stu.setSno(sno);
stu.setSname(sname);
stu.setSsex(ssex);
stu.setSage(sage);
JSONObject json = new JSONObject();
if(stuService.doUpdateStudent(stu)==1){
json.put("msg", "修改成功");
}else{
json.put("msg", "修改失敗");
}
PrintWriter writer = response.getWriter();
String callback = request.getParameter("callback");
String result = callback + "(" + json.toString() + ")";
writer.write(result);
}
4.5.3 通過學號刪除學生操作
private void doDeleteBySno(HttpServletRequest request,
HttpServletResponse response) throws IOException{
String sno = request.getParameter("sno");
JSONObject json = new JSONObject();
if(stuService.doDeleteBySno(sno)==1){
json.put("msg", "刪除成功");
}else{
json.put("msg", "刪除失敗");
}
PrintWriter writer = response.getWriter();
String callback = request.getParameter("callback");
String result = callback + "(" + json.toString() + ")";
writer.write(result);
}
五莫瞬、總結
? 對于mybatis框架的使用,主要還是在映射文件的配置醉锄,將數(shù)據(jù)庫內所查出的數(shù)據(jù)與實體類的映射乏悄,從而實現(xiàn)數(shù)據(jù)的持久化操作。
? MyBatis是一個優(yōu)秀的持久層框架恳不,它對jdbc的操作數(shù)據(jù)庫的過程進行封裝檩小,使開發(fā)者只需要關注 SQL 本身,而不需要花費精力去處理例如注冊驅動烟勋、創(chuàng)建connection规求、創(chuàng)建statement、手動設置參數(shù)卵惦、結果集檢索等jdbc繁雜的過程代碼阻肿。
對于前臺頁面,我會在下一篇文章中寫出沮尿,如上面觀點你們有所異議丛塌,歡迎大家給我指出较解。