一、开发流程

1)引jar包

//mybatis_core
mybatis3.4core\asm-5.2.jar
mybatis3.4core\cglib-3.2..jar
mybatis3.4core\commons-logging-1.2.jar
mybatis3.4core\log4j-1.2..jar
mybatis3.4core\mybatis-3.4..jar //db connector
DB-connector\mysql-connector-java-5.1.-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=""/>
</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(); } catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
} }

mybatis开发流程,增删改查的更多相关文章

  1. Mybatis实现简单增删改查

    Mybatis的简单应用 学习内容: 需求 环境准备 代码 总结: 学习内容: 需求 使用Mybatis实现简单增删改查(以下是在IDEA中实现的,其他开发工具中,代码一样) jar 包下载:http ...

  2. MyBatis简单的增删改查以及简单的分页查询实现

    MyBatis简单的增删改查以及简单的分页查询实现 <? xml version="1.0" encoding="UTF-8"? > <!DO ...

  3. Mybatis入门之增删改查

    Mybatis入门之增删改查 Mybatis如果操作成功,但是数据库没有更新那就是得添加事务了.(增删改都要添加)----- 浪费了我40多分钟怀疑人生后来去百度... 导入包: 引入配置文件: sq ...

  4. MyBatis -- 对表进行增删改查(基于注解的实现)

    1.MyBatis对数据库表进行增/删/改/查 前一篇使用基于XML的方式实现对数据库的增/删/改/查 以下我们来看怎么使用注解的方式实现对数据库表的增/删/改/查 1.1  首先须要定义映射sql的 ...

  5. SpringMVC,MyBatis商品的增删改查

    一.需求 商品的增删改查 二.工程结构 三.代码 1.Mapper层 (1) ItemsMapperCustom.java package com.tony.ssm.mapper; import ja ...

  6. 基于SSM之Mybatis接口实现增删改查(CRUD)功能

    国庆已过,要安心的学习了. SSM框架以前做过基本的了解,相比于ssh它更为优秀. 现基于JAVA应用程序用Mybatis接口简单的实现CRUD功能: 基本结构: (PS:其实这个就是用的Mapper ...

  7. mybatis中的增删改查操作

    在这一个部分,主要进行增删改查的示例书写. 增删改查可以基于xml的,也可以基于注解的方式. 一:对单条数据的查询 1.目录结构 这个使得目录更加清晰 2.User.java 这个使用以前的user表 ...

  8. ztree使用系列三(ztree与springmvc+spring+mybatis整合实现增删改查)

    在springmvc+spring+mybatis里整合ztree实现增删改查,上一篇已经写了demo,以下就仅仅贴出各层实现功能的代码: Jsp页面实现功能的js代码例如以下: <script ...

  9. HBuilder webApp开发 Websql增删改查操作

    来源:http://blog.csdn.net/zhuming3834/article/details/51471434 这段时间公司要求我们做原生iOS和安卓的都转做H5开发APP,使用的工具HBu ...

  10. MyBatis入门2_增删改查+数据库字段和实体字段不一致情况

    本文为博主辛苦总结,希望自己以后返回来看的时候理解更深刻,也希望可以起到帮助初学者的作用. 转载请注明 出自 : luogg的博客园 谢谢配合! 当数据库字段和实体bean中属性不一致时 之前数据库P ...

随机推荐

  1. Scala访问修饰符

    Scala 访问修饰符基本和Java的一样,分别有:private,protected,public. 如果没有指定访问修饰符符,默认情况下,Scala对象的访问级别都是 public. Scala ...

  2. WPF中的动画——(五)关键帧动画

    与 From/To/By 动画类似,关键帧动画以也可以以动画形式显示目标属性值. 和From/To/By 动画不同的是, From/To/By 动画只能控制在两个状态之间变化,而关键帧动画则可以在多个 ...

  3. minGW cygwin gnuwin32

    首先,三个的官方网站分别是: minGW:http://www.mingw.org cygwin:  http://www.cygwin.com gnuwin32:  https://sourcefo ...

  4. spring boot 利用redisson实现redis的分布式锁

    原文:http://liaoke0123.iteye.com/blog/2375469 利用redis实现分布式锁,网上搜索的大部分是使用java jedis实现的. redis官方推荐的分布式锁实现 ...

  5. 分公司下拉框赋值-从后台传到前端jsp

    我的旧代码  List<MetaBranchCfg> list = metaBranchCfgBO.queryAllBranchList();  request.setAttribute( ...

  6. Android内存优化3 了解java GC 垃圾回收机制1

    开篇废话 如果我们想要进行内存优化的工作,还是需要了解一下,但这一块的知识属于纯理论的,有可能看起来会有点枯燥,我尽量把这一篇的内容按照一定的逻辑来走一遍.首先,我们为什么要学习垃圾回收的机制,我大概 ...

  7. Java递归删除文件目录的方法

    public static void delDir(String path){ File dir=new File(path); if(dir.exists()){ File[] tmp=dir.li ...

  8. ubuntu中文设置方法

    1.首先打开ubuntu设置(右上角的齿轮),或者直接在左面找到设置,如下图所示. 2.然后点[language support]设置,如下图所示. 3.在弹出的窗口再点击[install]设置操作, ...

  9. Hibernate简介与实例

    一.Hibernate简介 1.什么是Hibernate? Hibernate是数据持久层的一个轻量级框架.数据持久层的框架有很多比如:iBATIS,myBatis,Nhibernate,Siena等 ...

  10. CocoSourcesCS 3

    CocoSourcesCS 3 /*---------------------------------------------------------------------- Compiler Ge ...