一、开发流程

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. [转]oracle 数据库、表空间、实例、服务之间的关系

    1.每个DATABASE--可包含多个INSTANCE--每个INSTANCE可包含多个TABLESPACE和USER等(授予USER读写TABLESPACE的权限)--每个TABLESPACE可包含 ...

  2. iOS 未读消息角标 仿QQ拖拽 简单灵活 支持xib(源码)

    一.效果 二.简单用法 超级简单,2行代码集成:xib可0代码集成,只需拖一个view关联LFBadge类即可 //一般view上加角标 _badge1 = [[LFBadge alloc] init ...

  3. MYSQL复习笔记1-物理文件和系统架构

    date:20140101auth:Jin 一.物理组成(一) 日志文件参考:http://dev.mysql.com/doc/refman/5.1/en/server-logs.html1.错误日志 ...

  4. 利用cURL请外部接口

    昨天有一个需求,就是需要把获取到的百度地图信息存储到百度地图LBS云储存上 看了一下LBS云储存,说白了就是通过接口操作云数据库,所以写了一个通用的cURL函数 代码如下: /** * @param ...

  5. errno错误码及含义(中文)

    /usr/include/asm/errno.h #define EPERM 1 /* Operation not permitted */操作不允许 #define ENOENT 2 /* No s ...

  6. tile xml格式

    <map> version: The TMX format version, generally 1.0. orientation: Map orientation. Tiled supp ...

  7. Docker创建centos的LNMP镜像

    前段时间重装了系统,今天刚好有时间,就用docker安装一个lnmp开发环境,下面是我的安装笔记. 1. 安装docker 这个就不说了,不会的可以看下我之前的文章<Docker介绍及安装> ...

  8. Java笔记11:JSP连接Oracle数据库

    1 建立Web项目 在D:\tomcat\webapps\中建立basicSyntax项目,在该项目中添加WEB-INF,WEB-INF\classes\,WEB-INF\lib\和WEB-INF\w ...

  9. sudo 添加

    sudo 添加 /etc/sudoers 找到root  ALL=(ALL)  ALL那一行, 复制之后,修改用户名:

  10. WPF一段代码搞定所有的点击事件

    用一个方法来控制转发所有的点击事件,界面图如下:    <Page x:Class="WPFNavigate.Index" xmlns="http://schema ...