目录

MyBatis学习系列一之环境搭建

MyBatis学习系列二——增删改查

MyBatis学习系列三——结合Spring

数据库的经典操作:增删改查。

在这一章我们主要说明一下简单的查询和增删改,并且对程序接口做了一些调整,以及对一些问题进行了解答。

1、调整后的结构图:

2、连接数据库文件配置分离:

  一般的程序都会把连接数据库的配置单独放在.properties 文件中,然后在XML文件中引用,示例如下:

  config.properties:

driver=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
username=phonesurvey
password=world

  mybatis-config.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>
<properties resource="config.properties" />
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="nankang/dao/agentDao.xml" />
</mappers>
</configuration>

3、SqlSession分离:

  SqlSeesion单独做成工具类,以便调用,示例如下:

SqlSessionHelper:

package nankang.util;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class SqlSessionHelper { public static SqlSessionFactory getSessionFactory(){
SqlSessionFactory sessionFactory = null;
String resource= "mybatis-config.xml";
try{
InputStream inputStream = Resources.getResourceAsStream(resource);
//Reader reader = Resources.getResourceAsReader(resource);
sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch(Exception ex){
ex.printStackTrace();
}
return sessionFactory;
}
}

  SqlSessionFactory创建时,根据Reader和InputStream都可以。

4、XML文件添加内容:

   agentDao.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="nankang.dao.AgentDao">
<!-- 根据Id查询 -->
<select id="selectAgentById" parameterType="string" resultType="nankang.po.Agent">
select * from Agent where AgentId=#{id}
</select>
<!-- 添加 -->
<insert id="insertAgent" parameterType="nankang.po.Agent">
insert into Agent(agentId, companyCode, LoginName, AgentPwd, AgentCode, Name, status,sysFlag)
values(#{agentId},'SHNK',#{loginName},'D41D8CD98F00B204E9800998ECF8427E',#{agentCode},#{name},1,1)
</insert>
<!-- 删除 -->
<delete id="deleteAgent" parameterType="string">
delete from Agent where agentid=#{id}
</delete>
<!-- 修改 -->
<update id="updateAgent" parameterType="nankang.po.Agent">
update agent set name=#{name} where agentid=#{agentId}
</update>
<!-- 查询所有 -->
<select id="selectAllAgent" resultType="nankang.po.Agent">
select * from Agent
</select>
<!-- 查询所有无返回对象 -->
<select id="selectAllAgent2" resultType="hashmap">
select * from Agent
</select> </mapper>

AgentDao.java:

package nankang.dao;

import java.util.List;
import java.util.Map; import nankang.po.Agent; import org.apache.ibatis.annotations.Select; public interface AgentDao {
//根据Id查询
public Agent selectAgentById(String Id);
//根据名称查询
@Select("select * from Agent where name=#{name}")
public Agent selectAgentByName(String name);
//添加
public int insertAgent(Agent agent);
//删除
public int deleteAgent(String id);
//修改
public int updateAgent(Agent agent);
//查询所有的
public List<Agent> selectAllAgent();
public List<Map<String, Object>> selectAllAgent2(); }

  1、XML文件中的语句,可以直接写在接口文件中,如:根据名称查询;

  2、其他参考示例。

  几个问题说明:

  1)如何查询数据集合?

    使用ResultType设置,返回用List<T>即可

  2)查询一条数据,如果为空,怎么判断?

    如果没有查询到数据,返回为NULL,进行空对象判断即可

  3)查询所有的集合,不放在构建对象的List中:

    resultType=map,返回类型 List<Map<String,Object>>,字段为空则不展示在Map中

  4)如何实现事务:

    SqlSession:commit,rollback,close

  

5、测试

package nankang.test;

import java.util.List;
import java.util.Map; import nankang.dao.AgentDao;
import nankang.util.SqlSessionHelper; import org.apache.ibatis.session.SqlSession; public class test { /**
* @param args
*/
public static void main(String[] args) { SqlSession sqlSession = SqlSessionHelper.getSessionFactory().openSession();
try{ AgentDao agentMapper = sqlSession.getMapper(AgentDao.class); //根据Id查询
// Agent agent = agentMapper.selectAgentById("SHNKAG00000000051");
// if(null != agent){
// System.out.println(agent.getName());
// }else{
// System.out.println("不存在该用户");
// }
// agent = agentMapper.selectAgentByName("1001");
// System.out.println(agent.getAgentId());
//查询所有
List<Map<String, Object>> agentList = agentMapper.selectAllAgent2();
System.out.println(agentList.size());
//添加
// Format format = new SimpleDateFormat("00yyyyMMddhhmmss");
// Calendar calendar = Calendar.getInstance();
// String dateStr = format.format(calendar.getTime());
// Agent agent = new Agent();
// agent.setAgentId(dateStr);
// agent.setLoginName("1111");
// agent.setAgentCode("aaaa");
// agent.setName("aaaa");
// int num = agentMapper.insertAgent(agent);
// System.out.println(num);
//删除
// int num = agentMapper.deleteAgent("0020150226093127");
// System.out.println(num);
//更新
// Agent agent = new Agent();
// agent.setAgentId("0020150226010005");
// agent.setName("Test");
// int num = agentMapper.updateAgent(agent);
// System.out.println(num); //增删改,提交
sqlSession.commit();
System.out.println("完成");
}catch(Exception ex){
sqlSession.rollback();
System.out.println(ex.getMessage());
}finally{
sqlSession.close();
} } }

  这边需要注意的是:SqlSession一定要close

6、源码下载:http://pan.baidu.com/s/1pJmeYpX (Fish的分享>MyBatis>myBatis2.rar)

MyBatis学习系列二——增删改查的更多相关文章

  1. MyBatis学习--简单的增删改查

    jdbc程序 在学习MyBatis的时候先简单了解下JDBC编程的方式,我们以一个简单的查询为例,使用JDBC编程,如下: Public static void main(String[] args) ...

  2. MyBatis学习之简单增删改查操作、MyBatis存储过程、MyBatis分页、MyBatis一对一、MyBatis一对多

    一.用到的实体类如下: Student.java package com.company.entity; import java.io.Serializable; import java.util.D ...

  3. Mybatis学习笔记3 - 增删改查示例

    1.接口定义 package com.mybatis.dao; import com.mybatis.bean.Employee; public interface EmployeeMapper { ...

  4. ASP.NET从零开始学习EF的增删改查

           ASP.NET从零开始学习EF的增删改查           最近辞职了,但是离真正的离职还有一段时间,趁着这段空档期,总想着写些东西,想来想去,也不是很明确到底想写个啥,但是闲着也是够 ...

  5. http://www.cnblogs.com/nangong/p/db29669e2c6d72fb3d0da947280aa1ce.htm ASP.NET从零开始学习EF的增删改查

    http://www.cnblogs.com/nangong/p/db29669e2c6d72fb3d0da947280aa1ce.htmlASP.NET从零开始学习EF的增删改查

  6. Mybatis实现数据的增删改查

    Mybatis实现数据的增删改查 1.项目结构(使用maven创建项目) 2.App.java package com.GetcharZp.MyBatisStudy; import java.io.I ...

  7. 数据库学习之数据库增删改查(另外解决Mysql在linux下不能插入中文的问题)(二)

    数据库增删改查 增加 首先我们创建一个数据库user,然后创建一张表employee create table employee( id int primary key auto_increment, ...

  8. mybatis学习系列二

    1 参数处理(封装map过程)(23) 1.1)F5进入断点:Employee employee1=mapper.selectEmployeeByMap(map); 1.2)进入MapperProxy ...

  9. idea+spring4+springmvc+mybatis+maven实现简单增删改查CRUD

    在学习spring4+springmvc+mybatis的ssm框架,idea整合简单实现增删改查功能,在这里记录一下. 原文在这里:https://my.oschina.net/finchxu/bl ...

随机推荐

  1. Input gameobject vector3 c#

    Input类中的常用方法 bool w=Input.GetKey(KeyCode.W);//检测是否按下键盘W Input.GetKeyDown(KeyCode.W);//表示检测按下时 Input. ...

  2. 十一、jdk命令之Jstatd命令(Java Statistics Monitoring Daemon)

    目录 一.jdk工具之jps(JVM Process Status Tools)命令使用 二.jdk命令之javah命令(C Header and Stub File Generator) 三.jdk ...

  3. eclipse导出jar包

    第一种:普通类导出jar包,我说的普通类就是指此类包含main方法,并且没有用到别的jar包. 1.在eclipse中选择你要导出的类或者package,右击,选择Export子选项: 2.在弹出的对 ...

  4. C++ 多继承和虚继承的内存布局(转)

    转自:http://www.oschina.net/translate/cpp-virtual-inheritance 警告. 本文有点技术难度,需要读者了解C++和一些汇编语言知识. 在本文中,我们 ...

  5. 建立dblink

    源地址:http://blog.itpub.net/24104981/viewspace-1116085/ create database link dblinkname connect to use ...

  6. C++primer 练习13.39

    13.39 编写你自己版本的StrVec,包括自己版本的reserve,capacity(参见9.4节,第318页)和resize(参见9.3.5节,第314页) 13.40 为你的StrVec类添加 ...

  7. MySQL主存复制与读写分离的感悟

    1.主存复制: 就是实现数据拷贝,有点实时的感觉,完成数据同步,存储两份数据. 项目开发中,类似场景许多,尤其是异构系统之间的交互,协作.-------------------场景目的:为了安全,各自 ...

  8. python 字典实现类似c的switch case

    #python 字典实现类似c的switch def print_hi(): print('hi') def print_hello(): print('hello') def print_goodb ...

  9. Java-convert between INT and STRING

    int -> String 三种写法 String s = 43 + ""; String s = String.valueOf(43); String s = Intege ...

  10. Codeforces Round #218 (Div. 2) D. Vessels

    D. Vessels time limit per test 2 seconds memory limit per test 256 megabytes input standard input ou ...