2.1 mongodb使用Java进行数据批量插入

合集下载

java批量插入数据方法

java批量插入数据方法

java批量插入数据方法【实用版2篇】目录(篇1)1.Java 批量插入数据的背景和需求2.Java 批量插入数据的方法3.批量插入数据的优点4.批量插入数据的注意事项正文(篇1)【Java 批量插入数据的背景和需求】在 Java 应用程序中,我们常常需要对数据库进行批量数据插入操作。

比如,在一个电商平台中,我们需要将大量商品信息插入到数据库中;在社交网络应用中,用户发表的信息可能需要批量插入到数据库。

在这种情况下,如何提高插入效率,降低系统资源消耗,成为 Java 开发者面临的一个问题。

【Java 批量插入数据的方法】Java 提供了两种主要的批量插入数据的方法:使用`PreparedStatement`和使用`Batch`语句。

1.使用`PreparedStatement``PreparedStatement`是 Java 中预编译 SQL 语句的一种方式,它能够有效地防止 SQL 注入攻击,并且提高 SQL 执行效率。

使用`PreparedStatement`进行批量插入数据的方法是,将所有要插入的数据按照 SQL 语句的格式组织好,然后使用`addBatch()`方法将这些数据添加到批处理中,最后使用`executeBatch()`方法一次性执行批处理中的所有 SQL 语句。

2.使用`Batch`语句`Batch`语句是 JDBC(Java Database Connectivity)中的一种批量处理语句,它能够将多个 SQL 语句组合在一起,一次性发送到数据库进行执行。

使用`Batch`语句进行批量插入数据的方法是,将所有要插入的数据按照 SQL 语句的格式组织好,然后使用`addBatch()`方法将这些数据添加到批处理中,最后使用`executeBatch()`方法一次性执行批处理中的所有 SQL 语句。

【批量插入数据的优点】批量插入数据有以下几个优点:1.提高插入效率:批量插入数据可以减少数据库的交互次数,从而提高插入效率。

mongodb数据库中插入数据

mongodb数据库中插入数据

mongodb数据库中插⼊数据⼀:connection 访问集合;在mongodb数据库中,数据是存储在许多数据集合中,可以使⽤数据库对象的collection⽅法访问⼀个集合。

该⽅法使⽤如下:db.collection(collectionName, [options], [callback]);collectionName参数值是⼀个字符串,⽤于指定需要访问的集合名,该参数是必须填写的。

options参数值为⼀个对象,⽤于指定访问该集合时使⽤的选项,使⽤的属性可以百度搜索下,选项⽐较多,⽤到的时候可以查下。

callback参数⽤于指定访问集合操作执⾏结束时的回调函数,该回调函数的指定⽅法如下:function(err, collection) {}在该回调函数中,可以使⽤⼆个参数,第⼀个参数值为访问对象操作失败时抛出的错误对象,第⼆个参数值为⼀个Collection对象,代表被访问的集合,当访问集合失败时,该参数值为null.⼆:Collection对象insert⽅法我们可以使⽤Collection对象的insert⽅法向该集合中插⼊⼀个数据⽂档,在该数据库中每⼀条数据都是⼀个数据⽂档。

该⽅法使⽤如下:collection.insert(docs, [options], [callback]);在insert⽅法中,有3个参数,docs为必选的参数,该参数值为⼀个JSON对象或⼀个由JSON对象构成的数组,⽤于指定需要插⼊的数据⽂档。

options参数为⼀个对象,⽤于指定插⼊数据时使⽤的选项,该属性具体值可以百度下,选项有点多,这⾥不介绍。

callback参数⽤于指定插⼊数据操作执⾏结束时的回调函数,如下:function(err, docs) {};在该回调函数中,可以使⽤两个参数,第⼀个参数为插⼊数据操作失败时抛出的错误对象,第⼆个参数值为⼀个JSON对象或由⼀个JSON 对象构成的数组,代表被插⼊的数据⽂档,当插⼊数据操作失败时,该参数值为null.下⾯是向数据库插⼊users集合,来插⼊⼀个数据⽂档。

java连接mongoDB并进行增删改查操作实例详解

java连接mongoDB并进行增删改查操作实例详解

java连接mongoDB并进⾏增删改查操作实例详解本⽂实例讲述了java连接mongoDB并进⾏增删改查操作。

分享给⼤家供⼤家参考,具体如下:1、安装 MongoDB JDBC驱动程序在java中使⽤mongoDB之前,⾸先需要拥有java连接mongoDB的第三⽅驱动包(jar包)1)maven项⽬可通过在pom.xml中添加依赖<dependencies><dependency><groupId>org.mongodb</groupId><artifactId>mongo-java-driver</artifactId><version>3.0.4</version></dependency></dependencies>2)⾮maven项⽬jar包下载地址:2、连接数据库将mongoDB JDBC驱动加⼊到项⽬之后,就可以对mongoDB进⾏操作了。

1)不通过认证连接mongoDB服务//连接到 mongodb 服务MongoClient mongoClient = new MongoClient("localhost", 27017);这⾥的 "localhost" 表⽰连接的服务器地址,27017 为端⼝号。

可以省略端⼝号不写,系统将默认端⼝号为 27017。

如://连接到 mongodb 服务,默认端⼝号为27017MongoClient mongoClient = new MongoClient("localhost");也可以将服务器地址和端⼝号都省略,系统默认服务器地址为 "localhost",端⼝号为 27017。

如://连接到 mongodb 服务,默认连接到localhost服务器,端⼝号为27017MongoClient mongoClient = new MongoClient();2)通过认证连接mongoDB服务List<ServerAddress> adds = new ArrayList<>();//ServerAddress()两个参数分别为服务器地址和端⼝ServerAddress serverAddress = new ServerAddress("localhost", 27017);adds.add(serverAddress);List<MongoCredential> credentials = new ArrayList<>();//MongoCredential.createScramSha1Credential()三个参数分别为⽤户名数据库名称密码MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray()); credentials.add(mongoCredential);//通过连接认证获取MongoDB连接MongoClient mongoClient = new MongoClient(adds, credentials);ServerAddress()两个参数 "localhost" , 27017 分别为服务器地址和端⼝。

Java操作mongoDB使用文档

Java操作mongoDB使用文档

Java Driver for MongoDB开发前准备:1.MongoDB连接url(e.g. localhost:27017)2.mongo-java-driver-2.9.3.jar(目前最新版)(用来查看api和帮助文档)一、连接MongoDB// MongoDB连接对象private Mongo mongoDBServer;// 根据host:port获取MongoDB连接对象mongoDBServer = new Mongo( host, port );// 数据库名private String database;// 从连接对象中获得相应数据库对象DB db = mongoDBServer.getDB( database );至此,我们已经打开了一个mongodb的连接,并且已经获得一个名为database的数据库(mongodb中成为collection集合)。

下面对这个集合进行增删改查操作。

进行操作前。

我们需要先使用数据库对象获取表(mongodb中的集合对象)。

// 获得名为person的表(又称集合)DBCollection dbcol = db.getCollection( "person" );二、新增操作(Add)// 新建一个map对象,将需要保存的数据放入map中map.put("key","value");…….// 用map对象创建一个MongoDB自带的DBObject对象用作插入操作参数DBObject param = new BasicDBObject( map );// 调用数据库集合对象的insert方法,传入DBObject对象执行插入操作WriteResult result = dbcol.insert( param );WriteResult对象是操作返回结果,我们可以用如下方法判断操作是否出错if ( result.getError() != null ){System.out.println( result.getError() );}至此新增操作完成。

mongodb插入数据语法

mongodb插入数据语法

mongodb插入数据语法MongoDB是一种非关系型数据库,它使用类似于JavaScript的语言进行数据操作。

在MongoDB中,插入数据的基本语法如下:1. 插入单个文档```javascriptdb.collectionName.insertOne({key1: value1, key2: value2, ...})```这个命令将一个包含键值对的文档插入到名为“collectionName”的集合中。

如果集合不存在,MongoDB将自动创建它。

2. 插入多个文档```javascriptdb.collectionName.insertMany([{document1}, {document2}, ...])```这个命令将一个包含多个文档的数组插入到集合中。

与`insertOne`不同,`insertMany`可以一次插入多个文档。

3. 插入文档并指定ID如果你想在插入文档时指定一个唯一的ID,可以使用以下语法:```javascriptdb.collectionName.insertOne({_id: ObjectId("600f58955874f70f79b7e55a"), key1: value1, key2: value2, ...})```在这个例子中,`_id`字段被指定为一个ObjectId类型的值,这是MongoDB中唯一标识符的类型。

如果你不指定`_id`字段,MongoDB会自动生成一个。

请注意,以上语法适用于MongoDB 3.x和更高版本。

如果你使用的是早期版本的MongoDB,可能需要使用不同的语法或方法来插入数据。

Java操作MongoDB插入数据进行模糊查询与in查询功能

Java操作MongoDB插入数据进行模糊查询与in查询功能

Java操作MongoDB插⼊数据进⾏模糊查询与in查询功能由于需要⽤MongoDB缓存数据,所以⾃⼰写了⼀套公共的存放和读取⽅法具体如下:存放mongodb:/*** 公共⽅法:设置Object类型缓存* @author shijing* @param param* @param sysGuid*/public void setObjData(Map<String,Object> param, String sysGuid, String enumBpd){DBObject dbObject = new BasicDBObject();dbObject.putAll(param);String collectionName = EnumBpd.getBpdType(enumBpd) + sysGuid;mongoDao.insertToCol(dbObject,collectionName);}/*** 公共⽅法:设置List缓存* @author shijing* @param paramList* @param sysGuid*/public void setListData(List<Map<String,Object>> paramList, String sysGuid, String enumBpd){List<DBObject> list = new ArrayList<>();if(CollectionUtils.isNotNull(paramList)){for (Map<String,Object> param : paramList){DBObject dbObject = new BasicDBObject();dbObject.putAll(param);list.add(dbObject);}}String collectionName = EnumBpd.getBpdType(enumBpd) + sysGuid;mongoDao.insertToCol(list,collectionName);mongoDao⾥⾯的⽅法:public void insertToCol(DBObject document, String collectionName) {dropCol(collectionName);DBCollection dbCollection = mongoTemplate.createCollection(collectionName);dbCollection.insert(document);}public void insertToCol(List<DBObject> documents, String collectionName) {dropCol(collectionName);DBCollection dbCollection = mongoTemplate.createCollection(collectionName);dbCollection.insert(documents);}读取⽅法/*** 通过关键字模糊查询问题和答案库* @param param* @return*/@Overridepublic List<Map<String, Object>> searchQuestionAndAnswerByKeyword(Map<String, Object> param) {List<Map<String,Object>> searchList = new ArrayList<>();Map<String,Object> userInfo = SessionUtils.getUserInfo();String sysGuid = userInfo.get("sys_guid").toString();String collectionName = EnumBpd.getBpdType(EnumBpd.HELP_PAGE_LIST.getType())+sysGuid;//注释⾥⾯这种⽅式虽然能模糊查询,但是容易漏掉数据,切记切记//Pattern pattern = pile("^.*" + param.get("keyword") +".*$", Pattern.CASE_INSENSITIVE);BasicDBObject query= new BasicDBObject();//模糊查询的字段设置query.put("page_html", pile((String) param.get("keyword")));DBCursor dbCursor = mongoDao.findAll(query,collectionName);List<DBObject> list = dbCursor.toArray();for (DBObject dbObject: list){searchList.add(dbObject.toMap());}//模糊查到的数据进⾏组装return getQuestionAndAnswerList(searchList);}/*** 公共⽅法:批量—— in⽅法查询List数据* @author shijing* @param ids id集合* @param paramMap 其他参数* @param columnName in字段列名* @param collectionName 表名* @return*/@Overridepublic List<Map<String, Object>> batchSearchPageListByIds(List<String> ids, Map<String,Object> paramMap, String columnName, String collectionName) {List<Map<String,Object>> searchList = new ArrayList<>();BasicDBObject query= new BasicDBObject();//批量查询,inif (CollectionUtils.isNotEmpty(ids)){BasicDBList values = new BasicDBList();values.addAll(ids);query.put(columnName, new BasicDBObject("$in",values));}//拼接参数if(MapUtils.isNotEmpty(paramMap)){for (String mapKey: paramMap.keySet()){query.put(mapKey, paramMap.get(mapKey));}}DBCursor dbCursor = mongoDao.findAll(query,collectionName);List<DBObject> list = dbCursor.toArray();if (dbCursor!=null && dbCursor.size()>0){for (DBObject dbObject: list){searchList.add(dbObject.toMap());}}return searchList;}/*** 公共⽅法:通过参数获取List数据* @author shijing* @param paramMap 参数* @param collectionName 表名* @return*/@Overridepublic List<Map<String, Object>> getListByParam(Map<String, Object> paramMap,String collectionName){ List<Map<String,Object>> searchList = new ArrayList<>();BasicDBObject query= new BasicDBObject();//拼接参数if(MapUtils.isNotEmpty(paramMap)){for (String mapKey: paramMap.keySet()){query.put(mapKey, paramMap.get(mapKey));}}DBCursor dbCursor = mongoDao.findAll(query,collectionName);List<DBObject> list = dbCursor.toArray();if (dbCursor!=null && dbCursor.size()>0){for (DBObject dbObject: list){searchList.add(dbObject.toMap());}}return searchList;}/*** 公共⽅法:通过参数获取Object数据* @author shijing* @param paramMap* @param collectionName 表名* @return*/@Overridepublic Map<String, Object> getObjectByParam(Map<String, Object> paramMap, String collectionName) { Map<String,Object> webSiteInfo = new HashMap<>();BasicDBObject query= new BasicDBObject();//拼接参数if(MapUtils.isNotEmpty(paramMap)){for (String mapKey: paramMap.keySet()){query.put(mapKey, paramMap.get(mapKey));}}DBObject dbObject = mongoDao.findOne(query,collectionName);if(dbObject!=null){return dbObject.toMap();}return webSiteInfo;}注意事项:mongodb模糊查询时Pattern pattern = pile("^.*" + param.get("keyword") +".*$"这种⽅式存在bug,容易漏掉数据应该使⽤下⾯这种⽅式:query.put("page_html", pile((String) param.get("keyword")));先记录到这吧,有需要在补充,批量in⽅法也在上述代码⾥⾯。

实例讲解Java批量插入、更新数据

实例讲解Java批量插入、更新数据

实例讲解Java批量插⼊、更新数据Java的批量添加数据,多个字段同时添加多条数据,我不知道你遇到过没有。

今天我们就以⼀个具体的实例来说⼀下Java的批量添加数据,⾯向的是Oracle数据库。

前台页⾯:<span style="font-size:14px;"><body class="main_body" scroll="no"><div class="employee_gun_dong"><form name="webform" method="post"><div class="main_content_bg"><div class="main_content_title"><div id="baseinfo" onclick="activeTabPanel(1)" style="margin-right:2px;" class="tab1">基本信息</div><div id="semsinfo" onclick="activeTabPanel(2)" style="margin-right:2px;" class="tab1" >页签1</div><div id="changeinfo" onclick="activeTabPanel(3)"style="margin-right:2px;" class="tab1" >页签2</div><div id="familyinfo" onclick="activeTabPanel(4)" style="margin-right:2px;" class="tab1" >页签3</div><div id="changeinfo" onclick="activeTabPanel(5)"style="margin-right:2px;" class="tab1" >页签4</div><div id="familyinfo" onclick="activeTabPanel(6)" style="margin-right:2px;" class="tab1" >页签5</div><div id="familyinfo" onclick="activeTabPanel(7)" style="margin-right:2px;" class="tab2" >页签6</div></div></div><div class="main_content_bg" id="bankCardDiv"><div class="main_middle_bg"><div class="main_content_title">信息展⽰<input id="addBank" type="button" value="新增⼀⾏" class="modul_button_operate" onclick="addNewRow();" /></div><div class="main_table_bg"><table id="parttable" width='100%' border='0' cellspacing='1' cellpadding='0' class='content_table_list'><tr><th class='content_table_number'>序号</th><th class='content_table_thnowarp'>属性1</th><th class='content_table_thnowarp'>属性2</th><th class='content_table_thnowarp'>属性3</th><th class='content_table_thnowarp'>属性4</th><th class='content_table_thnowarp'>属性5</th><th class='content_table_thnowarp'>属性6</th><th class='content_table_thnowarp'>属性7</th><th class='content_table_thnowarp'>属性8</th><th class='content_table_thnowarp'>属性9</th><th class='content_table_thnowarp'>操作</th></tr><c:if test="${fn:length(personFamilyInfoList) > 0}"><c:forEach items="${personFamilyInfoList}" var="personFamilyInfoList" varStatus="st"><tr><!-- 序号 --><td class="content_table_number">${st.count}<input type="hidden" name="personFamilyInfoList[${st.count-1}].SGuid" value="${personFamilyInfoList.SGuid}"/><input type="hidden" name="personFamilyInfoList[${st.count-1}].SPersonGuid" value="${personFamilyInfoList.SPersonGuid}"/><input type="hidden" name="personFamilyInfoList[${st.count-1}].SUnitGuid" value="${personFamilyInfoList.SUnitGuid }"><input type="hidden" name="personFamilyInfoList[${st.count-1}].isEnable" value="${personFamilyInfoList.isEnable }"></td><!-- 属性1--><td class="content_table_td_centernowrap"><input id="sFamilyName${st.count-1}" type="text" name="personFamilyInfoList[${st.count-1}].SFamilyName" class="content_content_input" maxlength="20" value="${personFamilyInfoList.SFamilyName}"></td><!-- 属性2--><td class="content_table_td_centernowrap"><input id="sFamilyIdcardNo${st.count-1}" type="text" name="personFamilyInfoList[${st.count-1}].SFamilyIdcardNo" class="content_content_input" maxlength="20" value="${personFamilyInfoList.SFamilyIdcardNo}"></td><!-- 属性3--><td class="content_table_td_centernowrap"><select id="iFamilySex${st.count-1}" name="personFamilyInfoList[${st.count-1}].IFamilySex"><zw:basedictlist itemCode="<%=Constants.I_PERSON_SEX %>" selectValue="${personFamilyInfoList.IFamilySex}"></zw:basedictlist></select><font color="red">*</font></td><!-- 属性4--><td class="content_table_td_centernowrap"><select id="sFamilyRelation${st.count-1}" name="personFamilyInfoList[${st.count-1}].SFamilyRelation"><zw:basedictlist itemCode="<%=Constants.S_FAMILY_RELATION %>" selectValue="${personFamilyInfoList.SFamilyRelation}"></zw:basedictlist></select><font color="red">*</font></td><!-- 属性5--><td class="content_table_td_centernowrap"><input id="sFamilyInsurancePlace${st.count-1}" type="text" name="personFamilyInfoList[${st.count-1}].SFamilyInsurancePlace" class="content_content_input" maxlength="20" value="${personFamilyInfoList.SFamilyInsurancePlace}"></td><!-- 属性6--><td class='content_table_td_centernowrap'><input id="sFamilyResidencePalce${st.count-1}" type="text" name="personFamilyInfoList[${st.count-1}].SFamilyResidencePalce" class="content_content_input" maxlength="20" value="${personFamilyInfoList.SFamilyResidencePalce}"></td><!-- 属性7--><td class="content_table_td_centernowrap"><input id="sFamilyPhone${st.count-1}" type="text" name="personFamilyInfoList[${st.count-1}].SFamilyPhone" class="content_content_input" maxlength="20" value="${personFamilyInfoList.SFamilyPhone}"></td><!-- 属性8--><td class="content_table_td_centernowrap"><input id="dDentifySucessDate${st.count-1}" type="text" name="personFamilyInfoList[${st.count-1}].DDentifySucessDate" value="${personFamilyInfoList.DDentifySucessDate}" onfocus="WdatePicker()" notnull="true" vdisp="⾸次参保时间" class= <font color="red">*</font></td><!-- 属性9--><td class="content_table_td_centernowrap"><input id="dDentifyLostDate${st.count-1}" type="text" name="personFamilyInfoList[${st.count - 1}].DDentifyLostDate" value="${personFamilyInfoList.DDentifyLostDate}" onfocus="WdatePicker()" notnull="true" vdisp="⾸次参保时间" class="conten </td><td class='content_table_td_centernowrap'>取消</td></tr></c:forEach></c:if></table></div></div></div><div class="main_content_bg"><div class="main_content_title"><table style="width:100%"><tr><td width="100%" align="center"><input id="btnNextstep" type="button" value="上⼀步" class="modul_button_operate" onclick="" /><input id="btnAdd" type="button" value="保存" class="modul_button_operate" onclick="saveOrUpdate()" /><input id="" type="button" value="完成" class="modul_button_operate" onclick="" /><input id="btnReturn" type="button" value="返回" class="modul_button_operate" onclick="" /></td></tr></table></div></div></form></div></body></span>javascript函数:<span style="font-family:KaiTi_GB2312;font-size:14px;"><script type="text/javascript">$(function(){loadCheck();});function loadCheck(){var trs = $('#parttable tr').length;if(trs == 1){addNewRow();}}//初始变量var num = 0;//页⾯计数变量var row = 1;//⾏增加计数变量var index = 2;//List列表计数变量function addNewRow(){var trNum = $('#parttable tr').length;if(trNum>1){row = trNum;num = trNum - 1;}var htmlText ='<tr>'+'<td class="content_table_number">'+row+'</td>'+'<td class="content_table_td_centernowrap">'+'<input id="sFamilyName'+num+'" type="text" name="personFamilyInfoList['+num+'].SFamilyName" class="content_content_input" maxlength="20"></td>'+'<td class="content_table_td_centernowrap">'+'<input id="sFamilyIdcardNo'+num+'" type="text" name="personFamilyInfoList['+num+'].SFamilyIdcardNo" class="content_content_input" maxlength="20"></td>'+'<td class="content_table_td_centernowrap">'+'<select id="iFamilySex'+num+'" name="personFamilyInfoList['+num+'].IFamilySex">'+'<zw:basedictlist itemCode="2000" selectValue="personFamilyInfoList['+num+'].IFamilySex"></zw:basedictlist>'+'</select><font color="red">*</font></td>'+'<td class="content_table_td_centernowrap">'+'<select id="sFamilyRelation'+num+'" name="personFamilyInfoList['+num+'].SFamilyRelation">'+'<zw:basedictlist itemCode="135" selectValue="personFamilyInfoList['+num+'].SFamilyRelation"></zw:basedictlist>'+'</select><font color="red">*</font></td>'+'<td class="content_table_td_centernowrap">'+'<input id="sFamilyInsurancePlace'+num+'" type="text" name="personFamilyInfoList['+num+'].SFamilyInsurancePlace" class="content_content_input" maxlength="20"></td>'+'<td class="content_table_td_centernowrap">'+'<input id="sFamilyResidencePalce'+num+'" type="text" name="personFamilyInfoList['+num+'].SFamilyResidencePalce" class="content_content_input" maxlength="20"></td>'+'<td class="content_table_td_centernowrap">'+'<input id="sFamilyPhone'+num+'" type="text" name="personFamilyInfoList['+num+'].SFamilyPhone" class="content_content_input" maxlength="20"></td>'+'<td class="content_table_td_centernowrap">'+'<input id="dDentifySucessDate'+num+'" type="text" name="personFamilyInfoList['+num+'].DDentifySucessDate" onfocus="WdatePicker()" notnull="true" vdisp="⾸次参保时间" class="content_content_input" size="18" maxlength="18" style="width:70px;" +'<td class="content_table_td_centernowrap">'+'<input id="dDentifyLostDate'+num+'" type="text" name="personFamilyInfoList['+num+'].DDentifyLostDate" onfocus="WdatePicker()" notnull="true" vdisp="⾸次参保时间" class="content_content_input" size="18" maxlength="18" style="width:70px;"/></td> +'<td class="content_table_td_centernowrap">'+'<a onclick="delInsuranceInfo(this);">取消</a>'+'</td>'+'</tr>';$("#parttable").append(htmlText);num = num + 1;row += 1;}//删除动态列表function delInsuranceInfo(t){if(row>0){row=row-1} else{return false;}$(t).parent().parent().remove();}//保存或修改function saveOrUpdate(){$.ajax({url: "personFamilyInfo_addOrUpdatePersonFamilyInfo_include_json.action",type: "POST",data: jQuery(document.forms[0]).serializeArray(),success: function(resObj) {//判断返回值if (resObj.trim() == 'true') {Ext.MessageBox.alert("提⽰","保存成功",function(){});}else if(resObj.trim() == 'update'){Ext.MessageBox.alert("提⽰","更新成功",function(){});} else {Ext.MessageBox.alert("提⽰","保存失败");}}});} </span><span style="font-family:KaiTi_GB2312;font-size:14px;"></script></span>后台添加⽅法:<span style="font-family:KaiTi_GB2312;font-size:14px;">/*** <p>Description: 批量添加多条信息</p>* @param personFamilyInfoList 实体列表* @return 布尔值,true为添加成功,否则为添加失败* @throws Exception* @author : gaoying* @update :* @date : 2015-7-20*/public boolean addPersonFamilyInfo(List<PersonFamilyInfo> personFamilyInfoList) throws Exception{boolean bool = false;if(personFamilyInfoList.size()>0 && personFamilyInfoList != null){for(int i=0; i<personFamilyInfoList.size(); i++){String personFamilyID = UUIDHexGenerator.getUUID();String sunitGuid = "11111111";String spersonGuid = "0000000";if(personFamilyInfoList.get(i) != null){personFamilyInfoList.get(i).setSGuid(personFamilyID);personFamilyInfoList.get(i).setSUnitGuid(sunitGuid);personFamilyInfoList.get(i).setSPersonGuid(spersonGuid);personFamilyInfoList.get(i).setIsEnable(0);personFamilyInfoList.get(i).setDOperateDate(new Date());//设置系统的当前时间为⽣效时间,失效时间置为空personFamilyInfoList.get(i).setDDentifySucessDate(new Date());personFamilyInfoList.get(i).setDDentifyLostDate(null);try {String sGuidString = personFamilyInfoService.saveNeedPk(personFamilyInfoList.get(i)).toString();if(!"".equals(sGuidString)&&sGuidString.length()>0){bool = true;}else{System.out.println("供养亲属信息表第"+i+"条信息存储失败!");bool = false;return bool;}} catch (Exception e) {e.printStackTrace();}}}}return bool;}</span>后台更新⽅法:<span style="font-family:KaiTi_GB2312;font-size:14px;">/*** <p>Description: 批量更新信息</p>* @param personFamilyInfolist 实体列表* @param personId ⼈员id* @return 布尔值,true代表更新成功,否则更新失败* @throws Exception* @author : gaoying* @update :* @date : 2015-7-20*/public void updatePersonFamilyInfo(List<PersonFamilyInfo> personFamilyInfolist, String personId) throws Exception{//根据⼈员id查询页⾯有多少条数据List<PersonFamilyInfo> oldPersonFamilyInfolist = personFamilyInfoService.getPersonFamilyInfoByPersonId(personId);int num = oldPersonFamilyInfolist.size();if(personFamilyInfolist != null&&personFamilyInfolist.size() > 0){//检查页⾯的信息是否有修改,然后更新到数据库for(int i = 0; i<num; i++){try{//设置⼀个布尔值,如果变动字段设置为false,如果不变动则设置为trueboolean bool = true;//判断哪些字段更改过if(!oldPersonFamilyInfolist.get(i).getSFamilyName().equals(personFamilyInfolist.get(i).getSFamilyName())){bool = false;}if(!oldPersonFamilyInfolist.get(i).getSFamilyIdcardNo().equals(personFamilyInfolist.get(i).getSFamilyIdcardNo())){bool = false;}if(!oldPersonFamilyInfolist.get(i).getIFamilySex().equals(personFamilyInfolist.get(i).getIFamilySex())){bool = false;}if(!oldPersonFamilyInfolist.get(i).getSFamilyRelation().equals(personFamilyInfolist.get(i).getSFamilyRelation())){bool = false;}if(!oldPersonFamilyInfolist.get(i).getSFamilyInsurancePlace().equals(personFamilyInfolist.get(i).getSFamilyInsurancePlace())){bool = false;}if(!oldPersonFamilyInfolist.get(i).getSFamilyResidencePalce().equals(personFamilyInfolist.get(i).getSFamilyResidencePalce())){bool = false;}if(!oldPersonFamilyInfolist.get(i).getSFamilyPhone().equals(personFamilyInfolist.get(i).getSFamilyPhone())){bool = false;}System.out.println("未更改前时间:"+oldPersonFamilyInfolist.get(i).getDDentifySucessDate().getTime());System.out.println("更改后的时间:"+personFamilyInfolist.get(i).getDDentifySucessDate().getTime());if(oldPersonFamilyInfolist.get(i).getDDentifySucessDate().getTime() != personFamilyInfolist.get(i).getDDentifySucessDate().getTime()){bool = false;}if(bool == false){//证明字段更改过//更新数据前,要把原来没改动的数据复制⼀条,添加进数据库,把系统的当前时间设为该条数据的失效时间PersonFamilyInfo personFamilyInfo = new PersonFamilyInfo();BeanUtils.copyProperties(oldPersonFamilyInfolist.get(i), personFamilyInfo);System.out.println("该条数据主键:" + personFamilyInfo.getSGuid());personFamilyInfo.setSGuid(UUIDHexGenerator.getUUID());System.out.println("设置主键:" + personFamilyInfo.getSGuid());personFamilyInfo.setDOperateDate(new Date());//将当前保存数据库的是否有效置为1:⽆效personFamilyInfo.setIsEnable(1);personFamilyInfo.setDDentifyLostDate(new Date());personFamilyInfoService.save(personFamilyInfo);//更新该条数据,把系统的当前时间设为系统的⽣效时间和操作时间,是否有效设为0:有效,失效时间为空personFamilyInfolist.get(i).setIsEnable(0);personFamilyInfolist.get(i).setDDentifySucessDate(new Date());personFamilyInfolist.get(i).setDOperateDate(new Date());personFamilyInfolist.get(i).setDDentifyLostDate(null);personFamilyInfoService.merge(personFamilyInfolist.get(i));}}catch (Exception e) {e.printStackTrace();}}}</span>这样,java多字段、多条数据批量添加的例⼦就完成了,主要要注意前台页⾯叠加出现多⾏的js函数和后台的添加和更新⽅法,⽤list接收,循环遍历进⾏添加。

MongoDB插入数据的3种方法

MongoDB插入数据的3种方法

MongoDB插⼊数据的3种⽅法下⾯是在inventory集合中插⼊⼀个三个字段的⽂档:复制代码代码如下:db.inventory.insert( { _id: 10, type: "misc", item: "card", qty: 15 } )在实⽰例中,⽂档有⼀个⽤户指定的值为10的_id字段,这个值必须在inventory集合中唯⼀。

调⽤update()⽅法使⽤upsert标志创建⼀个新⽂档当没有匹配查询条件的⽂档时。

下⾯的例⼦当inventory集合中没有包含{type:"books",item:"journal"}的⽂档时创建⼀个新⽂档:复制代码代码如下:db.inventory.update({ type: "book", item : "journal" },{ $set : { qty: 10 } },{ upsert :true })MongoDB添加_id字段和分配⼀个唯⼀的ObjectId作为它的值。

新⽂档包含来⾃查询<query>条件的item和type字段,和来⾃更新<update>参数的qty字段:复制代码代码如下:{ "_id" : ObjectId("51e8636953dbe31d5f34a38a"), "item" : "journal", "qty" : 10, "type" : "book" }使⽤save()⽅法插⼊⼀个⽂档,通过该⽅法保存⼀个不包含_id字段的⽂档或者包含_id字段但该字段值不存在集合中的⽂档。

下⾯的⽰例创建⼀个新的⽂档在inventory集合:复制代码代码如下:db.inventory.save( { type: "book", item: "notebook", qty: 40 } )MongoDB添加_id字段和分配⼀个唯⼀的ObjectId作为它的值。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
相关文档
最新文档