一、开发流程

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. js 根据开始日期和结束日期显示倒计时

    <html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Con ...

  2. 关于abstract class 和 interface

    1.abstract class 在 Java 语言中表示的是一种继承关系,一个类只能使用一次继承关系.但是,一个类却可以实现多个interface. 2.在abstract class 中可以有自己 ...

  3. pca主成份分析方法

    1.应用pca的前提 应用pca的前提是,连续信号具有相关性.相关性是什么,是冗余.就是要利用pca去除冗余. 2.pca的定义 pca是一种去除随机变量间相关性的线性变换.是一种常用的多元数据分析方 ...

  4. Lua学习笔记之开始

    在这节课的开始,按照国际惯例,一般学习一门新的语言,都是要打印出“Hello,world”,那么我们也不例外. Lua语言的打印跟其他语言一样,只要print(“Hello,World”),然后保存为 ...

  5. Openshift 用户,角色和RBAC

    OCP中的权限管理沿用的Kubernetes RBAC机制,授权模式主要取决于下面几个因数 Rules 针对主要对象的操作权限,比如建立Pod Sets of permitted verbs on a ...

  6. log4j设置,以及中文乱码,通过过滤器输出指定级别的日志,或者指定级别范围的日志

    配置文件为默认名字log4j.properties时,放在某个模块下的resources下即可,即使有多个模块的情况下,任意一个模块的resources下有这个默认名字的文件log4j.propert ...

  7. iOS:在OC中调用JS脚本

    示例一:在webView中调用js脚本进行搜索 1.首先导入JavaScriptCore.framework这个框架 2.创建webView.设置代理.请求手机端百度 #import "Vi ...

  8. (六)SSO之CAS框架扩展 改动CAS源代码实现与ESS动态password验证对接

    题记: 偶尔的偶尔我们会听到这个站点的数据泄露了,那个站点的用户数据泄露了.让用户又一次改动登录password,所以,对于用户数据安全性越发的引起我们的重视了,尤其是一些保密性要求高的站点.更须要添 ...

  9. 将本地jar包添加到maven中

    将需要引入的jar包拷贝到maven项目的WEB-INF/lib中 在pom.xml中配置如下: <dependency> <groupId>com.xxxxx.union&l ...

  10. Swing JTable 具体解释

    改变列头 flightTable.getTableHeader().setDefaultRenderer(new TableCellRenderer() { public Component getT ...