博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mybatis开发流程,增删改查
阅读量:6307 次
发布时间:2019-06-22

本文共 7444 字,大约阅读时间需要 24 分钟。

一、开发流程

1)引jar包

//mybatis_coremybatis3.4core\asm-5.2.jarmybatis3.4core\cglib-3.2.5.jarmybatis3.4core\commons-logging-1.2.jarmybatis3.4core\log4j-1.2.17.jarmybatis3.4core\mybatis-3.4.4.jar//db connectorDB-connector\mysql-connector-java-5.1.40-bin.jar

2)变写实体类Student

package com.huitong.entity;public class Student {        private Integer id;    private String sname;    private double salary;        public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getSname() {        return sname;    }    public void setSname(String sname) {        this.sname = sname;    }            public double getSalary() {        return salary;    }    public void setSalary(double salary) {        this.salary = salary;    }    @Override    public String toString() {        return sname + ":" + salary;    }}
View Code

3)写映射文件StudentMapper.xml,配置mybatis.xml

INSERT INTO student(sname, salary) VALUES("allen",34.23);
INSERT INTO student(sname, salary) VALUES(#{sname},#{salary});
UPDATE student SET sname=#{sname},salary=#{salary} WHERE id=#{id}
DELETE FROM student WHERE id=#{id}

注意:如果查询结果返回的对象和数据表中字段,名称名不一致,需要使用resultMap,否则使用resultType。

 

配置mybatis.xml

 

4)写工具类MybatisUtil

package com.huitong.util.mybatis;import java.io.IOException;import java.io.Reader;import java.sql.Connection;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class MybatisUtil {        private static ThreadLocal
threadLocal = new ThreadLocal
(); private static SqlSessionFactory sqlSessionFactorysion; //禁止通过new创建对象 private MybatisUtil(){} /** * 加载mybatis配置文件 */ static{ try { Reader reader = Resources.getResourceAsReader("mybatis.xml"); sqlSessionFactorysion = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * 获取sqlsession * @return */ public static SqlSession getSqlSession(){ SqlSession sqlSession = threadLocal.get(); if(sqlSession == null){ sqlSession = sqlSessionFactorysion.openSession(); threadLocal.set(sqlSession); } return sqlSession; } /** * 关闭sqlsession */ public static void closeSqlSession(){ SqlSession sqlSession = threadLocal.get(); if(sqlSession != null){ //关闭sqlsession sqlSession.close(); //分离当前线程与sqlsession关系 threadLocal.remove(); } } public static void main(String[] args) { Connection connection = MybatisUtil.getSqlSession().getConnection(); System.out.println(connection!=null?"连接成功":"没有连接成功"); } }
View Code

5)StudentDao数据持久层Dao

package com.huitong.dao;import java.util.List;import org.apache.ibatis.session.SqlSession;import com.huitong.entity.Student;import com.huitong.util.mybatis.MybatisUtil;import com.huitong.util.mybatis.mybatisutil2;public class StudentDao {        /**     * 增加学生     * @throws Exception     */    public void add() throws Exception{        SqlSession sqlSession = null;                try{            sqlSession = MybatisUtil.getSqlSession();            int n = sqlSession.insert("com.huitong.entity.StudentMapper.add");                        System.out.println(n);            sqlSession.commit();                    } catch (Exception e){            e.printStackTrace();            sqlSession.rollback();                    } finally {            MybatisUtil.closeSqlSession();                    }            }        public void add2(Student stu) throws Exception{        SqlSession sqlSession = null;                try{            sqlSession = MybatisUtil.getSqlSession();            int n = sqlSession.insert("com.huitong.entity.StudentMapper.add2",stu);                        System.out.println(n);            sqlSession.commit();                    } catch (Exception e){            e.printStackTrace();            sqlSession.rollback();                    } finally {            MybatisUtil.closeSqlSession();                    }            }        public Student getStudentById(int id) throws Exception{                SqlSession sqlSession = MybatisUtil.getSqlSession();                try{            Student student = sqlSession.selectOne(Student.class.getName() + ".getStudentById", id);            return student;        } catch(Exception e){            e.printStackTrace();            throw new RuntimeException(e);                    } finally {            MybatisUtil.closeSqlSession();        }                    }        public List
getAll() throws Exception{ SqlSession sqlSession = MybatisUtil.getSqlSession(); try{ return sqlSession.selectList(Student.class.getName() + ".getAll"); } catch(Exception e){ e.printStackTrace(); throw new RuntimeException(e); } finally { MybatisUtil.closeSqlSession(); } } public void update(Student stu) throws Exception{ SqlSession sqlSession = MybatisUtil.getSqlSession(); try{ int n = sqlSession.update(Student.class.getName() + ".update",stu); System.out.println(n); sqlSession.commit(); }catch(Exception e){ e.printStackTrace(); sqlSession.rollback(); throw new RuntimeException(e); }finally{ MybatisUtil.closeSqlSession(); } } public void delete(int id){ SqlSession sqlSession = MybatisUtil.getSqlSession(); try{ int n = sqlSession.delete(Student.class.getName() + ".delete", id); System.out.println(n); sqlSession.commit(); } catch(Exception e){ e.printStackTrace(); sqlSession.rollback(); throw new RuntimeException(e); } finally{ MybatisUtil.closeSqlSession(); } } public static void main(String[] args) { StudentDao studentDao = new StudentDao();// Student stu = new Student();// stu.setId(2);// stu.setSname("beed");// stu.setSalary(20.12);// try { studentDao.delete(3); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }}
View Code

 

转载地址:http://eenxa.baihongyu.com/

你可能感兴趣的文章
bootstrap新闻模块样式模板
查看>>
zzzzw_在线考试系统①准备篇
查看>>
App Store 审核被拒的23个理由
查看>>
剑指offer第二版-1.赋值运算符函数
查看>>
javascript 对象
查看>>
Android学习笔记——文件路径(/mnt/sdcard/...)、Uri(content://media/external/...)学习
查看>>
Echart:前端很好的数据图表展现工具+demo
查看>>
CATransform3D iOS动画特效详解
查看>>
Linux VNC黑屏(转)
查看>>
Java反射简介
查看>>
react脚手架应用以及iview安装
查看>>
shell学习之用户管理和文件属性
查看>>
day8--socket网络编程进阶
查看>>
node mysql模块写入中文字符时的乱码问题
查看>>
仍需"敬请期待"的微信沃卡
查看>>
分析Ajax爬取今日头条街拍美图
查看>>
内存分布简视图
查看>>
POJ 2918 求解数独
查看>>
如何学习虚拟现实技术vr? vr初级入门教程开始
查看>>
第4 章序列的应用
查看>>