MyBatis学习系列二——增删改查
目录
数据库的经典操作:增删改查。
在这一章我们主要说明一下简单的查询和增删改,并且对程序接口做了一些调整,以及对一些问题进行了解答。
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中:
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学习系列二——增删改查的更多相关文章
- MyBatis学习--简单的增删改查
jdbc程序 在学习MyBatis的时候先简单了解下JDBC编程的方式,我们以一个简单的查询为例,使用JDBC编程,如下: Public static void main(String[] args) ...
- MyBatis学习之简单增删改查操作、MyBatis存储过程、MyBatis分页、MyBatis一对一、MyBatis一对多
一.用到的实体类如下: Student.java package com.company.entity; import java.io.Serializable; import java.util.D ...
- Mybatis学习笔记3 - 增删改查示例
1.接口定义 package com.mybatis.dao; import com.mybatis.bean.Employee; public interface EmployeeMapper { ...
- ASP.NET从零开始学习EF的增删改查
ASP.NET从零开始学习EF的增删改查 最近辞职了,但是离真正的离职还有一段时间,趁着这段空档期,总想着写些东西,想来想去,也不是很明确到底想写个啥,但是闲着也是够 ...
- http://www.cnblogs.com/nangong/p/db29669e2c6d72fb3d0da947280aa1ce.htm ASP.NET从零开始学习EF的增删改查
http://www.cnblogs.com/nangong/p/db29669e2c6d72fb3d0da947280aa1ce.htmlASP.NET从零开始学习EF的增删改查
- Mybatis实现数据的增删改查
Mybatis实现数据的增删改查 1.项目结构(使用maven创建项目) 2.App.java package com.GetcharZp.MyBatisStudy; import java.io.I ...
- 数据库学习之数据库增删改查(另外解决Mysql在linux下不能插入中文的问题)(二)
数据库增删改查 增加 首先我们创建一个数据库user,然后创建一张表employee create table employee( id int primary key auto_increment, ...
- mybatis学习系列二
1 参数处理(封装map过程)(23) 1.1)F5进入断点:Employee employee1=mapper.selectEmployeeByMap(map); 1.2)进入MapperProxy ...
- idea+spring4+springmvc+mybatis+maven实现简单增删改查CRUD
在学习spring4+springmvc+mybatis的ssm框架,idea整合简单实现增删改查功能,在这里记录一下. 原文在这里:https://my.oschina.net/finchxu/bl ...
随机推荐
- JAVA 下拉列表和滚动条
//下拉列表和滚动条 import java.awt.*; import javax.swing.*; public class Jiemian7 extends JFrame{ JPanel mb1 ...
- contentProvider 内容提供者
http://blog.csdn.net/woshixuye/article/details/8280879 实例代码当数据需要在应用程序间共享时,我们就可以利用ContentProvider为数据定 ...
- Centos下yum配置lnmp环境
首先关闭SELINUX vi /etc/selinux/config #SELINUX=enforcing #注释掉 #SELINUXTYPE=tar ...
- LNMP安装了哪些软件?安装目录在哪?
LNMP官网:http://lnmp.org/faq/lnmp-software-list.html LNMP一键安装包除去安装所必须的依赖包,还会默认安装以下软件: Nginx.MySQL/Mari ...
- mongodb 数据导入导出
mongoexport 命令异常方便简单强大! 连接数据库: jkmiao@jkmiao-ipin:~$ mongo 192.168.1.xx:xxx/jd_58tc_raw 1. 导出10条数据到 ...
- Decorator装饰模式
动态地给一个对象增加一些额外的职责.就增加功能而言,Decorator模式比生成子类更为灵活. ——<设计模式>GoF 作用:在不影响其他对象的情况下,以动态.透明的方式给单个对象添加职责 ...
- Innosetup中将bat文件压缩到压缩包中
有时候在安装的过程中需要调用某些文件(bat或者exe等文件),但是只需要使用一次,然后就可以删掉该文件, 在Innosetup中应该这样操作: 1.在.iss脚本的[Files]章节写下: So ...
- 在SoCEDS环境下编译和更新preloader和uboot程序的方法
在SoCEDS环境下编译和更新preloader和uboot程序的方法 前面有介绍preloader在HPS boot过程中的的作用,接下来讲述下用户在SoCEDS环境下改如何编译preloade ...
- php中检查文件或目录是否存在的代码小结
检查文件或目录是否存在 ,我们使用了php中常用的函数file_exists,这个函数就可以实现我想要的功能,下面大家慢慢参考一下下面是一个简单的检查文件是否存在的实例代码: <?php $fi ...
- NSSet、NSMutableSet基本用法
NSSet.NSMutableSet基本用法 在Foundation框架中,提供了NSSet类,它是一组单值对象的集合,且NSSet实例中元素是无序,同一个对象只能保存一个. 一.不可变集合NSSet ...