List of usage examples for org.apache.ibatis.session SqlSession insert
int insert(String statement, Object parameter);
From source file:com.glaf.core.db.TableDataManager.java
License:Apache License
public void insertTableData(String systemName, String tableName, List<Map<String, Object>> rows) { com.glaf.core.config.Environment.setCurrentSystemName(systemName); TableDefinition tableDefinition = getTableDefinitionService().getTableDefinition(tableName); if (tableDefinition != null) { if (tableDefinition.getTableName() != null) { tableDefinition.setTableName(tableDefinition.getTableName().toUpperCase()); }//w ww .ja v a 2 s .c om List<ColumnDefinition> columns = getTableDefinitionService().getColumnDefinitionsByTableName(tableName); if (columns != null && !columns.isEmpty()) { SqlSession sqlSession = null; Connection conn = null; try { conn = DBConnectionFactory.getConnection(systemName); conn.setAutoCommit(false); sqlSession = getSqlSessionFactory().openSession(ExecutorType.BATCH, conn); Iterator<Map<String, Object>> iterator = rows.iterator(); while (iterator.hasNext()) { TableModel table = new TableModel(); table.setTableName(tableName); Map<String, Object> dataMap = iterator.next(); for (ColumnDefinition column : columns) { String javaType = column.getJavaType(); String name = column.getColumnName(); ColumnModel c = new ColumnModel(); c.setColumnName(name); c.setJavaType(javaType); Object value = dataMap.get(name); if (value == null) { value = dataMap.get(name.toLowerCase()); } if (value == null) { if (column.getName() != null) { value = dataMap.get(column.getName()); if (value == null) { value = dataMap.get(column.getName().toLowerCase()); } } } if (value != null) { if ("Integer".equals(javaType)) { value = ParamUtils.getInt(dataMap, name); } else if ("Long".equals(javaType)) { value = ParamUtils.getLong(dataMap, name); } else if ("Double".equals(javaType)) { value = ParamUtils.getDouble(dataMap, name); } else if ("Date".equals(javaType)) { value = ParamUtils.getTimestamp(dataMap, name); } else if ("String".equals(javaType)) { value = ParamUtils.getString(dataMap, name); } else if ("Clob".equals(javaType)) { value = ParamUtils.getString(dataMap, name); } c.setValue(value); table.addColumn(c); } } sqlSession.insert("insertTableData", table); } sqlSession.commit(); conn.commit(); } catch (Exception ex) { JdbcUtils.rollback(conn); logger.error(ex); ex.printStackTrace(); throw new RuntimeException(ex); } finally { JdbcUtils.close(sqlSession); JdbcUtils.close(conn); } } } }
From source file:com.glaf.core.db.TableDataManager.java
License:Apache License
public void insertTableData(String systemName, TableDefinition tableDefinition, List<Map<String, Object>> rows) { if (tableDefinition.getTableName() != null) { tableDefinition.setTableName(tableDefinition.getTableName().toUpperCase()); }/* ww w. jav a 2s . com*/ List<ColumnDefinition> columns = tableDefinition.getColumns(); if (columns != null && !columns.isEmpty()) { SqlSession sqlSession = null; Connection conn = null; try { conn = DBConnectionFactory.getConnection(systemName); conn.setAutoCommit(false); sqlSession = getSqlSessionFactory().openSession(ExecutorType.BATCH, conn); Iterator<Map<String, Object>> iterator = rows.iterator(); while (iterator.hasNext()) { TableModel table = new TableModel(); table.setTableName(tableDefinition.getTableName()); Map<String, Object> dataMap = iterator.next(); for (ColumnDefinition column : columns) { String javaType = column.getJavaType(); String name = column.getColumnName(); ColumnModel c = new ColumnModel(); c.setColumnName(name); c.setJavaType(javaType); Object value = dataMap.get(name); if (value == null) { value = dataMap.get(name.toLowerCase()); } if (value == null) { if (column.getName() != null) { value = dataMap.get(column.getName()); if (value == null) { value = dataMap.get(column.getName().toLowerCase()); } } } if (value != null) { if ("Integer".equals(javaType)) { value = ParamUtils.getInt(dataMap, name); } else if ("Long".equals(javaType)) { value = ParamUtils.getLong(dataMap, name); } else if ("Double".equals(javaType)) { value = ParamUtils.getDouble(dataMap, name); } else if ("Date".equals(javaType)) { value = ParamUtils.getTimestamp(dataMap, name); } else if ("String".equals(javaType)) { value = ParamUtils.getString(dataMap, name); } else if ("Clob".equals(javaType)) { value = ParamUtils.getString(dataMap, name); } c.setValue(value); table.addColumn(c); } } sqlSession.insert("insertTableData", table); } sqlSession.commit(); conn.commit(); } catch (Exception ex) { JdbcUtils.rollback(conn); logger.error(ex); ex.printStackTrace(); throw new RuntimeException(ex); } finally { JdbcUtils.close(sqlSession); JdbcUtils.close(conn); } } }
From source file:com.glaf.core.db.TableDataManager.java
License:Apache License
public Collection<TableModel> saveAll(String systemName, TableDefinition tableDefinition, String seqNo, Collection<TableModel> rows) { com.glaf.core.config.Environment.setCurrentSystemName(systemName); logger.debug("tableDefinition=" + tableDefinition); logger.debug("idColumn=" + tableDefinition.getIdColumn().toString()); if (tableDefinition.getTableName() != null) { tableDefinition.setTableName(tableDefinition.getTableName().toUpperCase()); }//from www . ja v a2 s . co m if (tableDefinition.isInsertOnly()) { return this.insertAll(systemName, tableDefinition, seqNo, rows); } Collection<String> aggregationKeys = new HashSet<String>(); Map<String, Object> colMap = new java.util.HashMap<String, Object>(); Map<String, Object> keyMap = new java.util.HashMap<String, Object>(); Map<String, String> exprMap = new java.util.HashMap<String, String>(); List<ColumnDefinition> exprColumns = new java.util.ArrayList<ColumnDefinition>(); ColumnModel idColumn = new ColumnModel(); ColumnDefinition idCol = tableDefinition.getIdColumn(); if (idCol != null && idCol.getColumnName() != null) { idColumn.setColumnName(idCol.getColumnName()); idColumn.setJavaType(idCol.getJavaType()); idColumn.setValueExpression(idCol.getValueExpression()); } Iterator<ColumnDefinition> iter = tableDefinition.getColumns().iterator(); while (iter.hasNext()) { ColumnDefinition cell = iter.next(); if (StringUtils.isNotEmpty(cell.getValueExpression())) { exprMap.put(cell.getColumnName(), cell.getValueExpression()); exprColumns.add(cell); } } logger.debug(exprMap); String keyCloumns = tableDefinition.getAggregationKeys(); if (StringUtils.isNotEmpty(keyCloumns)) { List<String> cols = StringTools.split(keyCloumns); if (cols != null && !cols.isEmpty()) { StringBuffer buffer = new StringBuffer(1000); Iterator<TableModel> iterator = rows.iterator(); while (iterator.hasNext()) { TableModel tableData = iterator.next(); /** * ?? */ colMap.clear(); buffer.delete(0, buffer.length()); for (ColumnModel cell : tableData.getColumns()) { colMap.put(cell.getColumnName(), cell.getValue()); } Iterator<String> it = cols.iterator(); while (it.hasNext()) { Object val = colMap.get(it.next()); if (val != null) { buffer.append(val.toString()); } else { buffer.append(""); } if (it.hasNext()) { buffer.append("_"); } } String aggregationKey = buffer.toString(); aggregationKeys.add(aggregationKey); tableData.setAggregationKey(aggregationKey);// ?? } if (aggregationKeys.size() > 0 && (aggregationKeys.size() % 200 == 0)) { TableModel model = new TableModel(); model.setTableName(tableDefinition.getTableName()); model.setIdColumn(idColumn); model.setAggregationKeys(aggregationKeys); List<Map<String, Object>> list = getTableDataService().getTableKeyMap(model); if (list != null && !list.isEmpty()) { for (Map<String, Object> dataMap : list) { Object id = ParamUtils.getObject(dataMap, "id"); if (id == null) { id = ParamUtils.getObject(dataMap, "ID"); } String aggregationKey = ParamUtils.getString(dataMap, "aggregationKey"); keyMap.put(aggregationKey, id); } } } } if (aggregationKeys.size() > 0) { TableModel model = new TableModel(); model.setTableName(tableDefinition.getTableName()); model.setIdColumn(idColumn); model.setAggregationKeys(aggregationKeys); List<Map<String, Object>> list = getTableDataService().getTableKeyMap(model); if (list != null && !list.isEmpty()) { for (Map<String, Object> dataMap : list) { Object id = ParamUtils.getObject(dataMap, "id"); if (id == null) { id = ParamUtils.getObject(dataMap, "ID"); } String aggregationKey = ParamUtils.getString(dataMap, "aggregationKey"); keyMap.put(aggregationKey, id); } } } List<TableModel> inertRows = new java.util.ArrayList<TableModel>(); List<TableModel> updateRows = new java.util.ArrayList<TableModel>(); logger.debug(" rows size = " + rows.size()); Iterator<TableModel> iterator = rows.iterator(); while (iterator.hasNext()) { TableModel tableData = iterator.next(); ColumnModel myPK = tableData.getIdColumn(); ColumnModel pkColumn = new ColumnModel(); pkColumn.setColumnName(idColumn.getColumnName()); pkColumn.setJavaType(idColumn.getJavaType()); for (ColumnModel column : tableData.getColumns()) { colMap.put(column.getColumnName(), column.getValue()); } if (keyMap.containsKey(tableData.getAggregationKey())) { Object id = keyMap.get(tableData.getAggregationKey()); pkColumn.setValue(id); tableData.setIdColumn(pkColumn); tableData.removeColumn(pkColumn); updateRows.add(tableData); } else { ColumnModel col = new ColumnModel(); col.setColumnName("AGGREGATIONKEY"); col.setJavaType("String"); col.setValue(tableData.getAggregationKey()); tableData.removeColumn(col); tableData.addColumn(col); for (ColumnDefinition c : exprColumns) { ColumnModel x = new ColumnModel(); x.setColumnName(c.getColumnName()); x.setJavaType(c.getJavaType()); x.setValueExpression(c.getValueExpression()); tableData.addColumn(x); } for (ColumnModel cell : tableData.getColumns()) { String expr = exprMap.get(cell.getColumnName()); if (StringUtils.isNotEmpty(expr)) { if (ExpressionConstants.NOW_EXPRESSION.equals(expr) || ExpressionConstants.CURRENT_YYYYMMDD_EXPRESSION.equals(expr)) { if (cell.getDateValue() == null) { cell.setDateValue(new Date()); cell.setValue(cell.getDateValue()); } } if (ExpressionConstants.ID_EXPRESSION.equals(expr)) { if (cell.getValue() == null) { if (StringUtils.equals(cell.getJavaType(), "Integer")) { cell.setValue(getEntityService().nextId().intValue()); } else if (StringUtils.equals(cell.getJavaType(), "Long")) { cell.setValue(getEntityService().nextId()); } else { cell.setValue(getEntityService().getNextId()); } } } if (ExpressionConstants.SEQNO_EXPRESSION.equals(expr)) { cell.setValue(seqNo); } if (ExpressionConstants.UUID_EXPRESSION.equals(expr)) { cell.setValue(UUID32.getUUID()); } } } if (myPK != null && myPK.getValue() != null) { pkColumn.setValue(myPK.getValue()); } else { if (StringUtils.equals(pkColumn.getJavaType(), "Integer")) { pkColumn.setValue(getEntityService().nextId().intValue()); } else if (StringUtils.equals(pkColumn.getJavaType(), "Long")) { pkColumn.setValue(getEntityService().nextId()); } else { pkColumn.setValue(getEntityService().getNextId()); } } tableData.removeColumn(pkColumn); tableData.addColumn(pkColumn); tableData.setIdColumn(pkColumn); inertRows.add(tableData); } } SqlSession sqlSession = null; Connection conn = null; try { conn = DBConnectionFactory.getConnection(systemName); conn.setAutoCommit(false); sqlSession = getSqlSessionFactory().openSession(ExecutorType.BATCH, conn); if (!inertRows.isEmpty()) { logger.debug("inert rows size:" + inertRows.size()); for (TableModel tableData : inertRows) { tableData.setTableName(tableDefinition.getTableName()); logger.debug(tableData.toString()); sqlSession.insert("insertTableData", tableData); } } if (!updateRows.isEmpty()) { logger.debug("update rows size:" + updateRows.size()); for (TableModel tableData : updateRows) { tableData.setTableName(tableDefinition.getTableName()); sqlSession.insert("updateTableDataByPrimaryKey", tableData); } } sqlSession.commit(); conn.commit(); } catch (Exception ex) { JdbcUtils.rollback(conn); logger.error(ex); ex.printStackTrace(); throw new RuntimeException(ex); } finally { JdbcUtils.close(sqlSession); JdbcUtils.close(conn); } return rows; } else { throw new RuntimeException("aggregationKeys is required."); } }
From source file:com.glaf.core.db.TableDataManager.java
License:Apache License
/** * ?JSON?// ww w . j a v a 2 s. c om * * @param tableName * @param jsonObject */ public void saveTableData(SqlSession sqlSession, String systemName, String tableName, JSONObject jsonObject) { com.glaf.core.config.Environment.setCurrentSystemName(systemName); TableDefinition tableDefinition = getTableDefinitionService().getTableDefinition(tableName); if (tableDefinition != null && tableDefinition.getIdColumn() != null) { if (tableDefinition.getTableName() != null) { tableDefinition.setTableName(tableDefinition.getTableName().toUpperCase()); } ColumnDefinition idColumn = tableDefinition.getIdColumn(); boolean insertData = true; Object primaryKey = null; if (idColumn.getColumnName() != null) { primaryKey = jsonObject.get(idColumn.getColumnName()); } else if (idColumn.getName() != null) { primaryKey = jsonObject.get(idColumn.getName()); } if (primaryKey != null) { insertData = false; } TableModel tableModel = new TableModel(); tableModel.setTableName(tableName); List<ColumnDefinition> columns = tableDefinition.getColumns(); if (columns != null && !columns.isEmpty()) { for (ColumnDefinition col : columns) { if (StringUtils.equalsIgnoreCase(idColumn.getColumnName(), col.getColumnName())) { continue; } String javaType = col.getJavaType(); String columnName = col.getColumnName(); String name = col.getName(); ColumnModel cm = new ColumnModel(); cm.setJavaType(javaType); cm.setColumnName(col.getColumnName()); Object value = null; if (jsonObject.containsKey(columnName)) { value = jsonObject.get(columnName); if (StringUtils.equalsIgnoreCase("Integer", javaType)) { if (value instanceof Integer) { cm.setValue(jsonObject.getInteger(columnName)); } else { cm.setValue(Integer.parseInt(value.toString())); } } else if (StringUtils.equalsIgnoreCase("Long", javaType)) { if (value instanceof Long) { cm.setValue(jsonObject.getLong(columnName)); } else { cm.setValue(Long.parseLong(value.toString())); } } else if (StringUtils.equalsIgnoreCase("Double", javaType)) { if (value instanceof Double) { cm.setValue(jsonObject.getDouble(columnName)); } else { cm.setValue(Double.parseDouble(value.toString())); } } else if (StringUtils.equalsIgnoreCase("Date", javaType)) { if (value instanceof Date) { cm.setValue(jsonObject.getDate(columnName)); } else if (value instanceof Long) { Long t = jsonObject.getLong(columnName); cm.setValue(new Date(t)); } else { cm.setValue(DateUtils.toDate(value.toString())); } } else if (StringUtils.equalsIgnoreCase("String", javaType)) { if (value instanceof String) { cm.setValue(jsonObject.getString(columnName)); } else { cm.setValue(value.toString()); } } else { cm.setValue(value); } } else if (jsonObject.containsKey(name)) { value = jsonObject.get(name); if (StringUtils.equalsIgnoreCase("Integer", javaType)) { if (value instanceof Integer) { cm.setValue(jsonObject.getInteger(name)); } else { cm.setValue(Integer.parseInt(value.toString())); } } else if (StringUtils.equalsIgnoreCase("Long", javaType)) { if (value instanceof Long) { cm.setValue(jsonObject.getLong(name)); } else { cm.setValue(Long.parseLong(value.toString())); } } else if (StringUtils.equalsIgnoreCase("Double", javaType)) { if (value instanceof Double) { cm.setValue(jsonObject.getDouble(name)); } else { cm.setValue(Double.parseDouble(value.toString())); } } else if (StringUtils.equalsIgnoreCase("Date", javaType)) { if (value instanceof Date) { cm.setValue(jsonObject.getDate(name)); } else if (value instanceof Long) { Long t = jsonObject.getLong(name); cm.setValue(new Date(t)); } else { cm.setValue(DateUtils.toDate(value.toString())); } } else if (StringUtils.equalsIgnoreCase("String", javaType)) { if (value instanceof String) { cm.setValue(jsonObject.getString(name)); } else { cm.setValue(value.toString()); } } else { cm.setValue(value); } } tableModel.addColumn(cm); } } if (insertData) { ColumnModel idCol = new ColumnModel(); idCol.setJavaType(idColumn.getJavaType()); if (StringUtils.equalsIgnoreCase("Integer", idColumn.getJavaType())) { idCol.setValue(getEntityService().nextId().intValue()); } else if (StringUtils.equalsIgnoreCase("Long", idColumn.getJavaType())) { idCol.setValue(getEntityService().nextId()); } else { idCol.setValue(getEntityService().getNextId()); } tableModel.setIdColumn(idCol); sqlSession.insert("insertTableData", tableModel); } else { ColumnModel idCol = new ColumnModel(); idCol.setJavaType(idColumn.getJavaType()); idCol.setValue(primaryKey); tableModel.setIdColumn(idCol); sqlSession.update("updateTableDataByPrimaryKey", tableModel); } } }
From source file:com.glaf.core.test.MyBatisBatchTest.java
License:Apache License
@Test public void testInsert() { SqlSessionFactory sqlSessionFactory = super.getBean("sqlSessionFactory"); SqlSession sqlSession = null; try {// www . ja va 2s.c o m sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false); long id = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { SysLog log = new SysLog(); log.setId(id + i); log.setAccount("test"); log.setCreateTime(new Date()); log.setIp("192.168.0.12"); log.setOperate("insert"); log.setContent("Test Insert"); sqlSession.insert("insertSysLog", log); if (i == 9999) { // throw new RuntimeException("throw exception"); } } sqlSession.commit(); } catch (Exception ex) { if (sqlSession != null) { sqlSession.rollback(); } ex.printStackTrace(); throw new RuntimeException(ex); } finally { if (sqlSession != null) { sqlSession.close(); } } }
From source file:com.glaf.core.test.MyBatisBatchTest2.java
License:Apache License
@Test public void testInsert() { SqlSessionFactory sqlSessionFactory = super.getBean("sqlSessionFactory"); SqlSession sqlSession = null; try {//from w w w. j a va 2 s.c o m Environment.setCurrentSystemName("wechat"); HibernateBeanFactory.reload(); sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false); long id = System.currentTimeMillis(); for (int i = 0; i < 1000; i++) { SysLog log = new SysLog(); log.setId(id + i); log.setAccount("test"); log.setCreateTime(new Date()); log.setIp("192.168.0.12"); log.setOperate("insert"); log.setContent("Test Insert"); sqlSession.insert("insertSysLog", log); if (i == 999) { // throw new RuntimeException("throw exception"); } } sqlSession.commit(); } catch (Exception ex) { if (sqlSession != null) { sqlSession.rollback(); } ex.printStackTrace(); throw new RuntimeException(ex); } finally { if (sqlSession != null) { sqlSession.close(); } } }
From source file:com.gordcorp.jira2db.persistence.MyBatisDao.java
License:Open Source License
/** * Method inserts the object into the table. </br></br> You will usually * override this method, especially if you're inserting associated objects. * </br> Example: </br> If your DAO object is called CarInfo.java, the * corresponding mapper query id should be: <insert id="createCarInfo" * ... </br></br> SQL Executed (example): insert into [tablename] * (fieldname1,fieldname2,...) values(value1,value2...) ... * //from w w w . j ava2 s . co m */ @Override public int create(T o) throws PersistenceException { SqlSession session = sf.openSession(); int status = -1; try { String query = NAMESPACE + "." + PREFIX_INSERT_QUERY + o.getClass().getSimpleName(); status = session.insert(query, o); // GenericDto genericDto = (GenericDto) o; // status = genericDto.getId(); session.commit(); } finally { session.close(); } return status; }
From source file:com.inform.project.dao.MyBatisAdminImpl.java
@Override public void addObject(LoginAuthModel user) { SqlSession session = null; try {//from w w w .j a v a 2s . co m session = MyBatisSession.getInst().getSession().openSession(); session.insert("GetUsersMapper.insertOne", user); session.commit(); } catch (IOException ex) { Logger.getLogger(MyBatisAdminImpl.class.getName()).log(Level.SEVERE, null, ex); } finally { if (session != null) { session.close(); } } }
From source file:com.inform.project.dao.MyBatisGetCategoryImpl.java
@Override public void setCategory(UserCategoryModel category) { SqlSession session = null; try {/*from w w w .j ava2s . c o m*/ session = MyBatisSession.getInst().getSession().openSession(); session.insert("GetUsersCategoryMapper.insertOne", category); session.commit(); } catch (IOException ex) { Logger.getLogger(MyBatisAdminImpl.class.getName()).log(Level.SEVERE, null, ex); } finally { if (session != null) { session.close(); } } }
From source file:com.inform.project.dao.MyBatisGetEventsImpl.java
@Override public void addEvent(EventModel event) { SqlSession session = null; try {/*from w w w .j av a 2 s . c o m*/ session = MyBatisSession.getInst().getSession().openSession(); session.insert("GetEventsModelMapper.insertOne", event); session.commit(); } catch (IOException ex) { Logger.getLogger(MyBatisAdminImpl.class.getName()).log(Level.SEVERE, null, ex); } finally { if (session != null) { session.close(); } } }