[MyBatis]完整MyBatis CRUD工程
下载地址:https://files.cnblogs.com/files/xiandedanteng/Person191005.rar
pom.xml:这个文件主要是引入依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.hy</groupId> <artifactId>fillMillionDatum</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>fillMillionDatum</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> </project>
mybatis-config.xml:这个文件主要配了DB连接信息和需要引入的Mapper
<?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> <settings> <setting name="logImpl" value="LOG4J"/> </settings> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <!-- 配置数据库连接信息 --> <dataSource type="UNPOOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://192.168.161.128:3306/test" /> <property name="username" value="root" /> <property name="password" value="12345678" /> </dataSource> </environment> </environments> <mappers> <mapper resource="PersonMapper.xml"></mapper> </mappers> </configuration>
PersonMapper.xml:这里定义进行CRUD的多条sql语句
<?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.hy.PersonMapper"> <select id="selectAll" resultType="com.hy.Person"> select id,name,enrollTime from person </select> <select id="insertPerson"> insert into person(id,name,enrollTime) values (#{id},#{name},#{enrolltime}) </select> <select id="selectOneById" resultType="com.hy.Person"> select id,name,enrollTime from person where id=#{id} </select> <update id="updatePersonNameById" parameterType="java.util.HashMap"> update person set name=#{name} where id=#{id} </update> <delete id="deletePersonsMonthsAgo" parameterType="java.util.HashMap"> delete from person where enrolltime<#{date} </delete> </mapper>
PersonMapper接口 这个和PersonMapper文件是对应的,可以把调DB的函数写在这里,也可以在代码里用id来调用。
package com.hy; public interface PersonMapper { Person selectOneById(long id); int updatePersonNameById(String name,long id); int deletePersonsMonthsAgo(String date); }
Person类:实体类
package com.hy; import java.text.MessageFormat; public class Person { private long id; private String name; private String enrolltime; public String toString() { Object[] arr={id,name,enrolltime}; String retval=MessageFormat.format("Person id={0},name={1},enrolltime={2}", arr); return retval; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEnrolltime() { return enrolltime; } public void setEnrolltime(String enrolltime) { this.enrolltime = enrolltime; } }
SelectAllPerson:全选方案
package com.hy; import java.io.Reader; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.log4j.Logger; public class SelectAllPerson { private static Logger logger = Logger.getLogger(SelectAllPerson.class); public static void main(String[] args) throws Exception{ long startTime = System.currentTimeMillis(); Reader reader=Resources.getResourceAsReader("mybatis-config.xml"); SqlSessionFactory ssf=new SqlSessionFactoryBuilder().build(reader); reader.close(); SqlSession session=ssf.openSession(); try { List<Person> list=session.selectList("selectAll"); for(Person emp:list) { System.out.println(emp); } long endTime = System.currentTimeMillis(); logger.info("Time elapsed:" + toDhmsStyle((endTime - startTime)/1000) + "."); }finally { session.close(); } } // format seconds to day hour minute seconds style // Example 5000s will be formatted to 1h23m20s public static String toDhmsStyle(long allSeconds) { String DateTimes = null; long days = allSeconds / (60 * 60 * 24); long hours = (allSeconds % (60 * 60 * 24)) / (60 * 60); long minutes = (allSeconds % (60 * 60)) / 60; long seconds = allSeconds % 60; if (days > 0) { DateTimes = days + "d" + hours + "h" + minutes + "m" + seconds + "s"; } else if (hours > 0) { DateTimes = hours + "h" + minutes + "m" + seconds + "s"; } else if (minutes > 0) { DateTimes = minutes + "m" + seconds + "s"; } else { DateTimes = seconds + "s"; } return DateTimes; } }
SelectOnePerson:按ID单找一个的方案
package com.hy; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.log4j.Logger; public class SelectOnePerson { private static Logger logger = Logger.getLogger(SelectOnePerson.class); public static void main(String[] args) throws Exception{ long startTime = System.currentTimeMillis(); Reader reader=Resources.getResourceAsReader("mybatis-config.xml"); SqlSessionFactory ssf=new SqlSessionFactoryBuilder().build(reader); reader.close(); SqlSession session=ssf.openSession(); try { PersonMapper pm=session.getMapper(PersonMapper.class); Person p=pm.selectOneById(9); logger.info("Selected person="+p); long endTime = System.currentTimeMillis(); logger.info("Time elapsed:" + toDhmsStyle((endTime - startTime)/1000) + "."); }finally { session.close(); } } // format seconds to day hour minute seconds style // Example 5000s will be formatted to 1h23m20s public static String toDhmsStyle(long allSeconds) { String DateTimes = null; long days = allSeconds / (60 * 60 * 24); long hours = (allSeconds % (60 * 60 * 24)) / (60 * 60); long minutes = (allSeconds % (60 * 60)) / 60; long seconds = allSeconds % 60; if (days > 0) { DateTimes = days + "d" + hours + "h" + minutes + "m" + seconds + "s"; } else if (hours > 0) { DateTimes = hours + "h" + minutes + "m" + seconds + "s"; } else if (minutes > 0) { DateTimes = minutes + "m" + seconds + "s"; } else { DateTimes = seconds + "s"; } return DateTimes; } }
UpdatePersonName:按ID更新一个人名字的方案
package com.hy; import java.io.Reader; import java.util.HashMap; import java.util.Map; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.log4j.Logger; public class UpdatePersonName { private static Logger logger = Logger.getLogger(UpdatePersonName.class); public static void main(String[] args) throws Exception{ long startTime = System.currentTimeMillis(); Reader reader=Resources.getResourceAsReader("mybatis-config.xml"); SqlSessionFactory ssf=new SqlSessionFactoryBuilder().build(reader); reader.close(); SqlSession session=ssf.openSession(); try { Map<String, String> para=new HashMap<String, String>(); para.put("id","1"); para.put("name","Andy"); int changed=session.update("updatePersonNameById", para); session.commit(); logger.info(changed+" record was changed."); long endTime = System.currentTimeMillis(); logger.info("Time elapsed:" + toDhmsStyle((endTime - startTime)/1000) + "."); }catch(Exception ex) { session.rollback(); }finally { session.close(); } } // format seconds to day hour minute seconds style // Example 5000s will be formatted to 1h23m20s public static String toDhmsStyle(long allSeconds) { String DateTimes = null; long days = allSeconds / (60 * 60 * 24); long hours = (allSeconds % (60 * 60 * 24)) / (60 * 60); long minutes = (allSeconds % (60 * 60)) / 60; long seconds = allSeconds % 60; if (days > 0) { DateTimes = days + "d" + hours + "h" + minutes + "m" + seconds + "s"; } else if (hours > 0) { DateTimes = hours + "h" + minutes + "m" + seconds + "s"; } else if (minutes > 0) { DateTimes = minutes + "m" + seconds + "s"; } else { DateTimes = seconds + "s"; } return DateTimes; } }
DeletePersonMonthAgo:按日期删除一批人的方案
package com.hy; import java.io.Reader; import java.util.HashMap; import java.util.Map; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.log4j.Logger; public class DeletePersonMonthAgo { private static Logger logger = Logger.getLogger(DeletePersonMonthAgo.class); public static void main(String[] args) throws Exception{ long startTime = System.currentTimeMillis(); Reader reader=Resources.getResourceAsReader("mybatis-config.xml"); SqlSessionFactory ssf=new SqlSessionFactoryBuilder().build(reader); reader.close(); SqlSession session=ssf.openSession(); try { Map<String, String> para=new HashMap<String, String>(); para.put("date","2020-01-01 00:01:00"); int changed=session.delete("deletePersonsMonthsAgo", para); session.commit(); logger.info(changed+" record was changed."); long endTime = System.currentTimeMillis(); logger.info("Time elapsed:" + toDhmsStyle((endTime - startTime)/1000) + "."); }catch(Exception ex) { session.rollback(); }finally { session.close(); } } // format seconds to day hour minute seconds style // Example 5000s will be formatted to 1h23m20s public static String toDhmsStyle(long allSeconds) { String DateTimes = null; long days = allSeconds / (60 * 60 * 24); long hours = (allSeconds % (60 * 60 * 24)) / (60 * 60); long minutes = (allSeconds % (60 * 60)) / 60; long seconds = allSeconds % 60; if (days > 0) { DateTimes = days + "d" + hours + "h" + minutes + "m" + seconds + "s"; } else if (hours > 0) { DateTimes = hours + "h" + minutes + "m" + seconds + "s"; } else if (minutes > 0) { DateTimes = minutes + "m" + seconds + "s"; } else { DateTimes = seconds + "s"; } return DateTimes; } }
InsertMillionPersons:插入六百四十万条Person记录(测试用,在我的T440p的虚拟机上的CentOS6.5上的MySql数据库耗时约一小时)
package com.hy; import java.io.Reader; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.log4j.Logger; public class InsertMillionPersons { private static Logger logger = Logger.getLogger(InsertMillionPersons.class); public static void main(String[] args) throws Exception{ Reader reader=Resources.getResourceAsReader("mybatis-config.xml"); SqlSessionFactory ssf=new SqlSessionFactoryBuilder().build(reader); reader.close(); SqlSession session=ssf.openSession(); long startTime = System.currentTimeMillis(); try { String currTime="2018-01-01 00:00:00"; for(long i=0;i<6400000;i++) { currTime=timePastTenSecond(currTime); Person emp=new Person(); emp.setId(i); emp.setName("Person:"+String.valueOf(i)); emp.setEnrolltime(currTime); int changed=session.insert("insertPerson", emp); logger.info("No."+i+" changed="+changed+" time:"+currTime); } session.commit(); long endTime = System.currentTimeMillis(); logger.info("Time elapsed:" + toDhmsStyle((endTime - startTime)/1000) + "."); }catch(Exception ex) { session.rollback(); }finally { session.close(); } } // 得到十秒后的时间 public static String timePastTenSecond(String otime) { try { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date dt=sdf.parse(otime); Calendar newTime = Calendar.getInstance(); newTime.setTime(dt); newTime.add(Calendar.SECOND,10);//日期加10秒 Date dt1=newTime.getTime(); String retval = sdf.format(dt1); return retval; } catch(Exception ex) { ex.printStackTrace(); return null; } } // format seconds to day hour minute seconds style // Exmplae 5000s will be formatted to 1h23m20s public static String toDhmsStyle(long allSeconds) { String DateTimes = null; long days = allSeconds / (60 * 60 * 24); long hours = (allSeconds % (60 * 60 * 24)) / (60 * 60); long minutes = (allSeconds % (60 * 60)) / 60; long seconds = allSeconds % 60; if (days > 0) { DateTimes = days + "d" + hours + "h" + minutes + "m" + seconds + "s"; } else if (hours > 0) { DateTimes = hours + "h" + minutes + "m" + seconds + "s"; } else if (minutes > 0) { DateTimes = minutes + "m" + seconds + "s"; } else { DateTimes = seconds + "s"; } return DateTimes; } }
InsertPersons:插入数条Person记录
package com.hy; import java.io.Reader; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.log4j.Logger; public class InsertPersons { private static Logger logger = Logger.getLogger(InsertPersons.class); public static void main(String[] args) throws Exception{ Reader reader=Resources.getResourceAsReader("mybatis-config.xml"); SqlSessionFactory ssf=new SqlSessionFactoryBuilder().build(reader); reader.close(); SqlSession session=ssf.openSession(); long startTime = System.currentTimeMillis(); try { String currTime="2018-01-01 00:00:00"; for(long i=0;i<10;i++) { currTime=timePastTenSecond(currTime); Person emp=new Person(); emp.setId(i); emp.setName("Person:"+String.valueOf(i)); emp.setEnrolltime(currTime); int changed=session.insert("insertPerson", emp); logger.info("No."+i+" changed="+changed+" time:"+currTime); } session.commit(); long endTime = System.currentTimeMillis(); logger.info("Time elapsed:" + toDhmsStyle((endTime - startTime)/1000) + "."); logger.info("Insert 10 persons completed."); }catch(Exception ex) { session.rollback(); }finally { session.close(); } } public static String timePastTenSecond(String otime) { try { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date dt=sdf.parse(otime); Calendar newTime = Calendar.getInstance(); newTime.setTime(dt); newTime.add(Calendar.SECOND,10);//日期加10秒 Date dt1=newTime.getTime(); String retval = sdf.format(dt1); return retval; } catch(Exception ex) { ex.printStackTrace(); return null; } } // format seconds to day hour minute seconds style // Exmplae 5000s will be formatted to 1h23m20s public static String toDhmsStyle(long allSeconds) { String DateTimes = null; long days = allSeconds / (60 * 60 * 24); long hours = (allSeconds % (60 * 60 * 24)) / (60 * 60); long minutes = (allSeconds % (60 * 60)) / 60; long seconds = allSeconds % 60; if (days > 0) { DateTimes = days + "d" + hours + "h" + minutes + "m" + seconds + "s"; } else if (hours > 0) { DateTimes = hours + "h" + minutes + "m" + seconds + "s"; } else if (minutes > 0) { DateTimes = minutes + "m" + seconds + "s"; } else { DateTimes = seconds + "s"; } return DateTimes; } }
使用这个程序,往一张Person表中插6,,400,000条记录花费约59分,删除3,153,605条记录(2019年1月1日之前)约用41秒,删除3153600条记录(2020年1月1日之前)约用49秒。
为什么在远程Oracle数据库上删花费时间要长的多?
--END-- 2019年10月5日20:39:39
[MyBatis]完整MyBatis CRUD工程的更多相关文章
- 使用MyBatis对表执行CRUD操作
一.使用MyBatis对表执行CRUD操作——基于XML的实现 1.定义sql映射xml文件 userMapper.xml文件的内容如下: <?xml version="1.0&quo ...
- MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作(转载)
本文转载自:http://www.cnblogs.com/jpf-java/p/6013540.html 上一篇博文MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybati ...
- MyBatis入门学习教程-使用MyBatis对表执行CRUD操作
上一篇MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对use ...
- MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作
一.使用MyBatis对表执行CRUD操作--基于XML的实现 1.定义sql映射xml文件 userMapper.xml文件的内容如下: 1 <?xml version="1.0&q ...
- MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作
上一篇博文MyBatis学习总结(一)——MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对u ...
- mybatis(二)执行CRUD操作的两种方式配置和注解
一.使用MyBatis对表执行CRUD操作——基于XML的实现 1.定义sql映射xml文件 userMapper.xml文件的内容如下: <?xml version="1.0&quo ...
- MyBatis学习总结_02_使用MyBatis对表执行CRUD操作
一.使用MyBatis对表执行CRUD操作——基于XML的实现 1.定义sql映射xml文件 userMapper.xml文件的内容如下: 1 <?xml version="1.0&q ...
- 【转】MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作
[转]MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作 上一篇博文MyBatis学习总结(一)——MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据, ...
- Mybatis的学习总结二:使用Mybatis对表进行CRUD操作【参考】
一.使用Mybatis对表进行CRUD操作------基于XML的实现 1.定义SQL的映射文件 2.在conf.xml中进行注册. 2.创建测试类 [具体过程参考:Mybatis的学习总结一] 二. ...
随机推荐
- 正则表达式 re模块的使用
一 正则表达式 首先, 我们在网页上进行行注册或者登陆的时候经常能看到一些格式上的错误提示. 比如:你在注册百度账号的时候 https://passport.baidu.com/v2/?reg&am ...
- SQL 递归查询,意淫CTE递归的执行步骤
今天用到了sql的递归查询.递归查询是CTE语句with xx as(....)实现的. 假如表Category数据如下. 我们想查找机枪这个子分类极其层次关系(通过子节点,查询所有层级节点).以下是 ...
- 00-c#与设计模式目录
工作5年多了,使用的语言是asp.net(c#),感觉自己遇到了技术瓶颈,以前一直忙着做兼职.接私活.加班,没有时间静下来好好想想自己的发展方向,就着春节期间放假,没事自己躺在老家的火炕上,问自己想要 ...
- CF666E Forensic Examination——SAM+线段树合并+倍增
RemoteJudge 题目大意 给你一个串\(S\)以及一个字符串数组\(T[1...m]\),\(q\)次询问,每次问\(S\)的子串\(S[p_l...p_r]\)在\(T[l...r]\)中的 ...
- Java笔记(基础第三篇)
面向对象的特点: 封装 继承 多态 类的构造方法 如果在类中定义的构造方法都不是无参的构造方法,则编译器不会为类设置一个默认的无参构造方法,当视图调用无参构造方法实例化一个对象时,编译器会报错,所以只 ...
- js替换文本内容。实例
<script language="javascript"> var r= "1\n2\n3\n"; //将字母\n替换成分号 alert(r.re ...
- 第二个爬虫之爬取知乎用户回答和文章并将所有内容保存到txt文件中
自从这两天开始学爬虫,就一直想做个爬虫爬知乎.于是就开始动手了. 知乎用户动态采取的是动态加载的方式,也就是先加载一部分的动态,要一直滑道底才会加载另一部分的动态.要爬取全部的动态,就得先获取全部的u ...
- PHP解决h5页面跨域
前端h5 页面请求后端接口会出现跨域, PHP 只需三行代码即可解决 //解决前端跨域(h5页面) header("Access-Control-Allow-Origin:*"); ...
- Comet OJ - Contest #11 D isaster 重构树+倍增+dfs序+线段树
发现对于任意一条边,起决定性作用的是节点编号更大的点. 于是,对于每一条边,按照节点编号较大值作为边权,按照最小生成树的方式插入即可. 最后用线段树维护 dfs 序做一个区间查询即可. Code: # ...
- HDOJ4467 ( 分块 思想 )
题目:链接:http://acm.hdu.edu.cn/showproblem.php?pid=4467 题意:给你n个点(每个点都有一个颜色,0代表黑色,1代表白色),m条边,每条边有一个权值.现在 ...