一、Mybatis本地dtd环境配置、
1、将Mybatis的jar包、数据库的jar包、log4j的jar包添加到项目路径中
2、先将mybatis-3-config.dtd放入src目录下,然后在src目录下配Mybatis.xml文件
Mybatis.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "//UNKNOWN/" "mybatis-3-config.dtd"> <configuration> <environments default="default"> <environment id="default"> <!-- 使用jdbc的事务 --> <transactionManager type="JDBC" /> <!-- 采用连接池 --> <dataSource type="POOLED"> <!-- 数据连接参数 --> <property name="url" value="jdbc:oracle:thin:@localhost:1521:accp"/> <property name="driver" value="oracle.jdbc.driver.OracleDriver"/> <property name="username" value="scott"/> <property name="password" value="tiger"/> </dataSource> </environment> </environments> <!-- 实体类映射文件集合 --> <mappers> <!-- 映射Emp.xml --> <mapper resource="com/accp/entity/Emp.xml"/> </mappers> </configuration>
3、构建MybatisUtil工具类
/**
* mybatis工具
* @author Administrator
*
*/
public class MyBatisUtil {
//保存会话集合
private static final ThreadLocal<SqlSession> tl = new ThreadLocal<SqlSession>();
private static SqlSessionFactory factory;
static{
try {
//读取文件流
Reader reader = Resources.getResourceAsReader("mybatis.xml");
//解析XML返回工厂
SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
factory = factoryBuilder.build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取会话
* @return
*/
public static SqlSession getSession(){
SqlSession session = tl.get();
if(session == null){
session = factory.openSession();
tl.set(session);
}
return session;
}
/**
* 关闭会话
*/
public static void closeSession(){
SqlSession session = tl.get();
if(session != null){
session.close();
tl.set(null);
}
}
}
4、新建实体类Emp,然后放入mybatis-3-mapper.dtd,配置Emp.xml,最后将Emp.xml映射到Mybatis.xml中
实体Emp.java,省略构造,getter,setter,以及重写toString()
package com.accp.entity;
/**
* 员工实体类
*/
public class Emp {
private Integer empno; //员工编号
private String ename; //姓名
private String job; //工种
private Integer mgr; //经理
private Float comm; //年终福利
private Float sal; //薪水
private Integer deptno; //部门编号
private Date hiredate; //入职日期
}
Emp.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "//UNKNOWN/" "mybatis-3-mapper.dtd"> <!-- 需要指定namespace,可以自定义为包名加类名 --> <mapper namespace="com.accp.entity.Emp"> <!-- id用于标识select语句,resultType指定返回结果类型 需为完整的包名+类名 --> <select id="selectEmp" resultType="com.accp.entity.Emp"> select * from emp </select> </mapper>
Mybatis.xml
<!-- 实体类映射文件集合 --> <mappers> <!-- 映射Emp.xml --> <mapper resource="com/accp/entity/Emp.xml"/> </mappers>
注意:如果数据库表中的列与实体类中的属性不一样还需配置
<!-- 设置resultMAP 用于实体类属性名和表中列名不一样 --> <!-- type:实体类 id:自定义的名称,用于resultType --> <resultMap type="com.accp.entity.Emp" id="empno_ename_Map"> <!-- property:实体类中的属性 column:表中的列 --> <result property="empno" column="empno"/> <result property="ename" column="ename"/> <result property="job" column="job"/> <result property="mgr" column="mgr"/> <result property="hiredate" column="hiredate"/> <result property="sal" column="sal"/> <result property="comm" column="comm"/> <result property="deptno" column="deptno"/> </resultMap>相应的select语句返回类型需由resultMap设置,而不是resultType
<select id="selectEmpResultMap" parameterType="com.accp.entity.Emp" resultMap="empno_ename_Map">
5、最后不要忘了把mybatis-3-config.dtd和mybatis-3-mapper.dtd放入项目根目录下
二、Mybatis基础增、删、改、查
1、查询所有Emp
public class Test1 {
/**
* 使用Mybatis查询所有Emp
*/
public static void main(String[] args) {
//声明会话
SqlSession ses = null;
try{
//获得会话
ses = MyBatisUtil.getSession();
//获得Emp集合
List<Emp> list = ses.selectList("selectEmp");
//遍历集合
for(Emp e : list){
System.out.println(e);
}
}catch (Exception e) {
e.printStackTrace();
}finally{
//关闭会话
if(ses != null){
MyBatisUtil.closeSession();
}
}
}
}
Emp.xml:
<!-- id用于标识select语句,resultType指定返回结果类型 需为完整的包名+类名 --> <select id="selectEmp" resultType="com.accp.entity.Emp"> select * from emp </select>2、查询单个对象,直接传参
public class Test2 {
/**
* 查询单个对象,直接传值
*/
public static void main(String[] args) {
//声明会话
SqlSession ses = null;
try {
//获得会话
ses = MyBatisUtil.getSession();
//查询单个Emp
Emp emp = ses.selectOne("selectOne",7369);
System.out.println(emp);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(ses != null){
MyBatisUtil.closeSession();
}
}
}
}
Emp.xml:
<!-- parameterType设置参数类型,int是Java的类型 --> <select id="selectOne" resultType="com.accp.entity.Emp" parameterType="int"> <!-- #{ }的内容可以自定义 --> select * from emp where empno = #{id} </select>3、查询多个对象,使用对象传参
public class Test3 {
/**
* 查询单个对象使用selectOne 查询多个对象使用selectList
* 使用对象传参
*/
public static void main(String[] args) {
SqlSession ses = null;
try {
ses = MyBatisUtil.getSession();
Emp emp = new Emp(null, "L");
List<Emp> list = ses.selectList("selectEmpByObj",emp);
for(Emp e : list){
System.out.println(e);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
MyBatisUtil.closeSession();
}
}
}
Emp.xml:
<!-- 使用对象传参 --> <select id="selectEmpByObj" resultType="com.accp.entity.Emp" parameterType="com.accp.entity.Emp"> select * from emp <where> <if test="empno > 0"> empno = #{empno} </if> <!-- test条件中and不能改成&& --> <!-- 如果前面条件不成立 sql中and会自动去掉--> <if test="ename != null and ename != ''"> <!-- #会根据数据加引号'',$直接填值 --> and ename like '%${ename}%' </if> </where> </select>4、查询多个对象,使用Map传参
/**
* 使用Map传参
*/
public static void main(String[] args) {
//声明会话
SqlSession ses = null;
try {
//获得会话
ses = MyBatisUtil.getSession();
//实例化map集合,并添加元素作为查询的条件
Map<String,Object> map = new HashMap<String,Object>();
//map.put("empno", 7369);
map.put("ename", "L");
//获得Emp集合,使用Map集合作为参数
List<Emp> list = ses.selectList("selectEmpByMap",map);
for(Emp e : list){
System.out.println(e);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Emp.xml:
<!-- 使用Map集合传参 --> <select id="selectEmpByMap" resultType="com.accp.entity.Emp" parameterType="map"> select * from emp <where> <if test="empno > 0"> empno = #{empno} </if> <!-- test条件中and不能改成&& --> <!-- 如果前面条件不成立 sql中and会自动去掉--> <if test="ename != null and ename != ''"> <!-- #会根据数据加'',$直接填值 --> and ename like '%${ename}%' </if> </where> </select>5、查询部分列,返回仍为对象
public class Test5 {
/**
* 查询部分列
*/
public static void main(String[] args) {
//声明会话
SqlSession ses = null;
try {
//获得会话
ses = MyBatisUtil.getSession();
//实例化Emp,作为查询参数
Emp emp = new Emp();
//emp.setEmpno(7369);
emp.setEname("L");
//获得Emp集合,返回值为List<Emp>,非查询列为null
List<Emp> list = ses.selectList("selectEmpResultMap", emp);
//输出对应列
for(Emp e : list){
System.out.println(e.getEname() + "\t" + e.getSal());
}
} catch (Exception e) {
e.printStackTrace();
}finally{
//关闭会话
if(ses != null){
MyBatisUtil.closeSession();
}
}
}
}
Emp.xml:
<select id="selectEmpResultMap" parameterType="com.accp.entity.Emp" resultMap="empno_ename_Map"> select ename,sal from emp <where> <if test="empno > 0"> empno = #{empno} </if> <!-- test条件中and不能改成&& --> <!-- sql语句前要加and --> <!-- 如果前面条件不成立 sql中and会自动去掉--> <if test="ename != null and ename != ''"> <!-- #会根据数据加'',$直接填值 --> and ename like '%${ename}%' </if> </where> </select>6、新增
public class Test6 {
/**
* Mybatis新增
*/
public static void main(String[] args) {
//声明会话
SqlSession ses = null;
try {
//获得会话
ses = MyBatisUtil.getSession();
//实例化Emp对象并赋值
Emp emp = new Emp();
emp.setEmpno(1010);
emp.setEname("张三");
emp.setJob("testJob");
emp.setMgr(7369);
emp.setHiredate(new Date());
emp.setSal(2000f);
emp.setComm(500f);
emp.setDeptno(10);
//插入数据返回受影响行数
int count = ses.insert("insertEmp",emp);
System.out.println(count);
//提交会话
ses.commit();
} catch (Exception e) {
e.printStackTrace();
//回滚会话
ses.rollback();
}finally{
//关闭会话
if(ses != null){
MyBatisUtil.closeSession();
}
}
}
}
Emp.xml:
<!-- sql结尾不能有分号; --> <insert id="insertEmp" parameterType="com.accp.entity.Emp"> insert into emp values(#{empno},#{ename},#{job},#{mgr},#{hiredate},#{sal},#{comm},#{deptno}) </insert>7、修改
public class Test7 {
/**
* Mybatis修改
*/
public static void main(String[] args) {
//声明会话
SqlSession ses = null;
try {
//获得会话
ses = MyBatisUtil.getSession();
//实例化Emp对象并赋值要修改的属性
Emp emp = new Emp();
emp.setEmpno(1010);
emp.setEname("李四");
//插入数据返回受影响行数
int count = ses.update("updateEmp",emp);
System.out.println(count);
//提交会话
ses.commit();
} catch (Exception e) {
e.printStackTrace();
//回滚会话
ses.rollback();
}finally{
//关闭会话
if(ses != null){
MyBatisUtil.closeSession();
}
}
}
}
Emp.xml:
<update id="updateEmp" parameterType="com.accp.entity.Emp"> update emp <set> <!-- 后面要加逗号, --> <if test="ename != null and ename != ''"> ename = #{ename}, </if> </set> where empno = #{empno} </update>8、删除
public class Test8 {
/**
* Mybatis删除
*/
public static void main(String[] args) {
//声明会话
SqlSession ses = null;
try {
//获得会话
ses = MyBatisUtil.getSession();
//实例化Emp对象并赋值要修改的empno
Emp emp = new Emp();
emp.setEmpno(1010);
//插入数据返回受影响行数
int count = ses.delete("deleteEmp",emp);
System.out.println(count);
//提交会话
ses.commit();
} catch (Exception e) {
e.printStackTrace();
//回滚会话
ses.rollback();
}finally{
//关闭会话
if(ses != null){
MyBatisUtil.closeSession();
}
}
}
}
Emp.xml:
<!-- 根据empno删除员工 --> <delete id="deleteEmp" parameterType="com.accp.entity.Emp"> delete emp where empno = #{empno} </delete>