闲来无聊,自己学习一下MyBatis框架,没想到书上简单的东西,作为新手居然花了一个下午才把环境搭建完,记录一下,以便以后查看
1、MyBatis介绍
- MyBatis 的前身是 iBatis,iBatis一词来源于"internet"和"abatis"的组合,是一个基于Java的持久层框架
- MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架
- MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索
- MyBatis使用简单的XML或注解用于配置和原始映射
2.开发环境
Eclipse4.3(额外下载MyBatis Generator插件)
MyBatis3.3的jar包
Oracle11g
ojdbc.jar
3.开发准备
3.1)在Oracle数据库中创建INFOS表,包含字段ID,STUID,STUNAME,GENDER
3.2)在New Project中创建新项目MybatisGenerat后,再选择由MyBatis Gerator插件提供逆向生成工具
3.3)在生成的generatorConfig.xml文件中将对应参数进行修改,如下
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration >
<context id="Test" >
<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
connectionURL="jdbc:oracle:thin:@192.168.xxx.xxx:1521:tc83" userId="admin" password="admin" />
<javaModelGenerator targetPackage="orm" targetProject="Test" />
<sqlMapGenerator targetPackage="orm" targetProject="Test" />
<javaClientGenerator targetPackage="orm" targetProject="Test" type="XMLMAPPER" />
<table schema="admin" tableName="INFOS" >
<generatedKey column = "id" sqlStatement="select S_incret.nextval from dual"
identity="false"/>
</table>
</context>
</generatorConfiguration>
修改后右键点击生成的XML文件选择如下选项后既生成数据库中标对应的POJO对象
3.4)新建Web项目MyBatisTest,在WEB-INF文件下的lib文件中将ojdbc.jar,mybatis-3.3.0.jar包导入并在项目中引用
3.4.1.
新建mybatis-config.xml文件置于dbtools包下,该配置文件主要定义了如何连接数据库以及数据库所必须的username,password及url等参数
mybatisconfig.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>
<!-- 当时把environments写成enviorments没把我郁闷死,细节决定成败。主要表示默认是开发模式-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<!-- 配置数据库连接信息 -->
<dataSource type="POOLED">
<property name="driver" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@192.168.xxx.xxx:1521:TC83"/>
<property name="username" value="admin" />
<property name="password" value="admin" />
</dataSource>
</environment>
</environments>
<!-- 映射文件 -->
<mappers>
<mapper resource="orm/InfosMapping.xml"/>
</mappers>
</configuration>
3.4.2新建orm包,将刚才逆向生成的java文件放入该包中,并新建InfosMapping.xml文件
InfosMapping.xml文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!-- 如果是比较懒是复制粘贴网上的头文件配置,务必记得下面是 DOCTYPE mapper ,否则会报头文件错误信息-->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<!-- mapper的命名空间 -->
<mapper namespace = "mybatis.testcurd">
<insert id="insertInfo" parameterType="orm.Infos">
<!-- 这里的resultType务必要跟反向生成POJO文件中id类型相同,这段话的意思是ID是根据数据库中序列自增添加的 -->
<selectKey resultType="java.lang.Short" keyProperty="id"
order="BEFORE">
select S_incret.nextval from dual
</selectKey>
insert into
INFOS(STUID,STUNAME,GENDER,ID)
values(#{stuid},#{stuname},#{gender},#{id})
</insert>
<select id="getInfoById" parameterType="int" resultType="orm.Infos">
select * from
infos where id=#{id}
</select>
<delete id="deleteInfoById" parameterType="int">
delete from
infos where id=#{id}
</delete>
<select id="selectAllInfo" resultType="orm.Infos">
select * from infos
</select>
<update id="updateInfosById" parameterType="orm.Infos">
update infos set stuid=#{stuid},stuname=#{stuname},gender=#{gender},id=#{id}
where id=#{id}
</update>
</mapper>
3.4.3 在dbtools包下新建 GetSqlSession.java,其实这里最好使用单例模式写,因为关乎SqlSessionFactory生命周期问题,为了更直观表示就先写成这样了,下一篇改过来(实际项目中请务必写成单例模式)
package dbtools;
import java.io.InputStream;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class GetSqlSession {
public static SqlSession getSqlSession(){
//由于我的mybatis-config.xml文件与GetSqlSession.java是在同一包下,所以直接用名字代替,务必注意路径问题,这些小问题很烦人的
String resource="mybatis-config.xml";
InputStream input=GetSqlSession.class.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(input);
SqlSession sqlsession=sqlSessionFactory.openSession();
return sqlsession;
}
}
3.4.4. 新建包controler,并新建Servlet InsertInfo.java文件用于插入多条记录(后面附上CRUD其他操作)
/**
*
*/
package controler;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import dbtools.GetSqlSession;
import orm.Infos;
public class InsertInfos extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse reponse){
Infos info=new Infos();
info.setStuid("stu001");
info.setStuname("mark");
info.setGender("Boy");
SqlSession sqlSession=GetSqlSession.getSqlSession();
//对应InfosMapping.xml文件中namespace与方法的id
sqlSession.insert("mybatis.testcurd.insertInfo",info);
System.out.println(info.getId());
sqlSession.commit();
sqlSession.close();
}
}<span style="font-size:14px;">
</span>
3.4.5 web.xml文件配置servlet
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>Test</servlet-name> <!-- 名字随便 -->
<servlet-class>controler.InsertInfos</servlet-class> <!-- servlet类名-->
</servlet>
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/Test</url-pattern> <!-- url访问虚拟路径,最后我们就是通过工程名/login进行访问的,像这样http://127.0.0.1:8000/LoginAction/login-->
</servlet-mapping>
</web-app>
3.5)完整项目列表(当时疏忽将controler包携程controoler了,丢人啊)
通过Tomcat运行servlet后查看数据库表中是否添加字段就能知道成功没啦
4.0 遇到的问题
本来感觉挺简单的框架搭建结果却搞了我一下午,主要遇到了以下问题
1.路径问题,mybatis中文件间的映射导致路径必须要小心小心再小心。
2.粗心问题,编写代码粗心总是将一些固定的东西写成习以为常的错误,主要还是代码敲的太少了
3.类型问题,在Mapping文件中的数据类型务必要与反向生成的POJO文件一致,否则会出现无法插入的问题
附:
1.查找某个ID的数据
package controler;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import dbtools.GetSqlSession;
import orm.Infos;
public class GetInfosById extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse reponse){
SqlSession sqlSession=GetSqlSession.getSqlSession();
Infos info=sqlSession.selectOne("mybatis.testcurd.getInfoById", 1);
System.out.println(info.getStuid());
System.out.println(info.getStuname());
System.out.println(info.getClass());
System.out.println(info.getId());
sqlSession.commit();
sqlSession.close();
}
}
2.查询所有记录
package controler;
import java.util.List;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import dbtools.GetSqlSession;
import orm.Infos;
public class GetAllInfos extends HttpServlet {
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
SqlSession sqlSession=GetSqlSession.getSqlSession();
List<Infos> listInfos=sqlSession.selectList("mybatis.testcurd.selectAllInfo");
for(int i = 0;i<listInfos.size();i++){
Infos info=listInfos.get(i);
System.out.println(info.getStuid()+info.getStuname()+info.getClass());
}
sqlSession.commit();
sqlSession.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3.更新记录
package controoler;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import dbtools.GetSqlSession;
import orm.Infos;
/**
* Servlet implementation class UpdateInfosById
*/
@WebServlet("/UpdateInfosById")
public class UpdateInfosById extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
SqlSession sqlsession = GetSqlSession.getSqlSession();
Infos info = sqlsession.selectOne("mybatis.testcurd.getInfoById", 1);
info.setStuname("Liming");
sqlsession.update("mybatis.testcurd.updateInfosById", info);
sqlsession.commit();
sqlsession.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
4.删除记录
package controoler;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import dbtools.GetSqlSession;
/**
* Servlet implementation class DeleteInfoById
*/
@WebServlet("/DeleteInfoById")
public class DeleteInfoById extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
SqlSession sqlsession =GetSqlSession.getSqlSession();
sqlsession.delete("mybatis.testcurd.deleteInfoById",1);
sqlsession.commit();
sqlsession.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}