mybatis开发流程,增删改查
一、开发流程
1)引jar包
//mybatis_core mybatis3.4core\asm-5.2.jar mybatis3.4core\cglib-3.2.5.jar mybatis3.4core\commons-logging-1.2.jar mybatis3.4core\log4j-1.2.17.jar mybatis3.4core\mybatis-3.4.4.jar //db connector DB-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; } }
3)写映射文件StudentMapper.xml,配置mybatis.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"> <mapper namespace="com.huitong.entity.Student"> <!-- 映射实体域表的关系 type:实体全路径名 id:映射唯一名 --> <resultMap type="com.huitong.entity.Student" id="studentMap"> <!-- id:主键属性 result:非主键属性 property:实体属性名 column:表的字段 --> <id column="id" property="id"/> <result column="sname" property="sname"/> <result column="salary" property="salary"/> </resultMap> <!-- insert:插入语句 parameterType:方法参数,如果是类:必须使用类全路径 --> <insert id="add"> INSERT INTO student(sname, salary) VALUES("allen",34.23); </insert> <insert id="add2" parameterType="com.huitong.entity.Student" > INSERT INTO student(sname, salary) VALUES(#{sname},#{salary}); </insert> <select id="getStudentById" parameterType="int" resultType="com.huitong.entity.Student"> SELECT id,sname,salary FROM student WHERE id=#{id}; </select> <select id="getAll" resultType="com.huitong.entity.Student"> SELECT id,sname,salary FROM student; </select> <update id="update" parameterType="com.huitong.entity.Student"> UPDATE student SET sname=#{sname},salary=#{salary} WHERE id=#{id} </update> <delete id="delete" parameterType="int"> DELETE FROM student WHERE id=#{id} </delete> </mapper>
注意:如果查询结果返回的对象和数据表中字段,名称名不一致,需要使用resultMap,否则使用resultType。
配置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> <environments default="mysql"> <environment id="mysql"> <transactionManager type="jdbc"></transactionManager> <dataSource type="pooled"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///day14?useSSL=true"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/huitong/entity/StudentMapper.xml"/> </mappers> </configuration>
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<SqlSession> threadLocal = new ThreadLocal<SqlSession>(); 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?"连接成功":"没有连接成功"); } }
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<Student> 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); } } }
学习过程中,难免出错。如果您在阅读过程中遇到不太明白,或者有疑问。欢迎指正...联系邮箱crazyCodeLove@163.com
如果觉得有用,想赞助一下请移步赞助页面:赞助一下
分类:
java web 基础知识
标签:
mybatis开发流程
, 增删改查
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2016-05-14 python中如果函数后面有多于一个括号是怎么回事?
2016-05-14 python函数中参数是如何传递的?