一、开发流程

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. FeignClient与RestTemplate的区别比较简单研究

    题外:个人觉得可能还没达到那种境界,还体会不到真正的实质性区别,就好比用HttpClient可以实现的用FeignClient同样可以实现,反之也是. JAVA 项目中接口调用怎么做 ? Httpcl ...

  2. (转)DLL中导出函数的两种方式(dllexport与.def文件)

    DLL中导出函数的两种方式(dllexport与.def文件)http://www.cnblogs.com/enterBeijingThreetimes/archive/2010/08/04/1792 ...

  3. WinCE6.0 2012年补丁下载地址

    Windows CE6.0 2012年补丁包WinCEPB60-121231-Product-Update-Rollup-Armv4I.msi下载地址:http://www.microsoft.com ...

  4. 重设WebLogic AdminServer的密码

    1.先停止运行的WebLogic Server $ $DOMAIN_HOME/bin/stopWebLogic.sh 2.迁移AdminServer下的数据目录 $ mv $DOMAIN_HOME/s ...

  5. 关于Java代码优化的44条建议!

    关于Java代码优化的N条建议! 本文是作者:五月的仓颉 结合自己的工作和平时学习的体验重新谈一下为什么要进行代码优化.在修改之前,作者的说法是这样的: 就像鲸鱼吃虾米一样,也许吃一个两个虾米对于鲸鱼 ...

  6. ylbtech-LanguageSamples-Porperties(属性)

    ylbtech-Microsoft-CSharpSamples:ylbtech-LanguageSamples-Porperties(属性) 1.A,示例(Sample) 返回顶部 “属性”示例 本示 ...

  7. 如何理解redo和undo

    redo和undo的区别    redo--> undo-->datafileinsert一条记录时, 表跟undo的信息都会放进 redo 中, 在commit 或之前, redo 的信 ...

  8. unity 显示mipmaplevel

    https://docs.unity3d.com/ScriptReference/Texture2D.SetPixels.html 显示mipmaplevel 需要贴图可读写不压缩 using Uni ...

  9. Druid对比Redshift

    Redshift 内部使用了亚马逊取得了授权的ParAccel 实时注入数据 抛开可能的性能不同, 有功能性的不同 Druid 适合分析大数据量的流式数据, 也能够实时加载和聚合数据一般来讲, 传统的 ...

  10. Android 常见内存泄漏的解决方式

    在Android程序开发中.当一个对象已经不须要再使用了,本该被回收时.而另外一个正在使用的对象持有它的引用从而导致它不能被回收.这就导致本该被回收的对象不能被回收而停留在堆内存中,内存泄漏就产生了. ...