Java Code Examples for org.springframework.jdbc.support.KeyHolder

The following are top voted examples for showing how to use org.springframework.jdbc.support.KeyHolder. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: nbone   File: NamedJdbcDao.java   Source Code and License 8 votes vote down vote up
@Override
public Object add(Object object) {
	SqlModel<Object> sqlModel = sqlBuilder.insertSelectiveSql(object);
	checkSqlModel(sqlModel);
	
	SqlParameterSource paramSource =  new BeanPropertySqlParameterSource(object);
	KeyHolder generatedKeyHolder =  new  GeneratedKeyHolder();
	namedPjdbcTemplate.update(sqlModel.getSql(), paramSource, generatedKeyHolder);
	Number num = generatedKeyHolder.getKey();
	
	String[] primaryKeys = sqlModel.getPrimaryKeys();
	if(primaryKeys != null && primaryKeys.length > 0){
		BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);
		beanWrapper.setPropertyValue(primaryKeys[0], num);
	}
	
	return object;
}
 
Example 2
Project: mybatis-dynamic-sql   File: SpringTest.java   Source Code and License 7 votes vote down vote up
@Test
public void testInsert() {
    GeneratedAlwaysRecord record = new GeneratedAlwaysRecord();
    record.setId(100);
    record.setFirstName("Bob");
    record.setLastName("Jones");
    
    InsertStatementProvider<GeneratedAlwaysRecord> insertStatement = insert(record)
            .into(generatedAlways)
            .map(id).toProperty("id")
            .map(firstName).toProperty("firstName")
            .map(lastName).toProperty("lastName")
            .build()
            .render(RenderingStrategy.SPRING_NAMED_PARAMETER);
    
    SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(insertStatement.getRecord());
    KeyHolder keyHolder = new GeneratedKeyHolder();
    
    int rows = template.update(insertStatement.getInsertStatement(), parameterSource, keyHolder);
    String generatedKey = (String) keyHolder.getKeys().get("FULL_NAME");
    
    assertThat(rows).isEqualTo(1);
    assertThat(generatedKey).isEqualTo("Bob Jones");
    
}
 
Example 3
Project: EasyTransaction   File: OrderService.java   Source Code and License 6 votes vote down vote up
private Integer saveOrderRecord(JdbcTemplate jdbcTemplate, final int userId, final long money) {
	
	final String INSERT_SQL = "INSERT INTO `order` (`order_id`, `user_id`, `money`, `create_time`) VALUES (NULL, ?, ?, ?);";
	KeyHolder keyHolder = new GeneratedKeyHolder();
	jdbcTemplate.update(
	    new PreparedStatementCreator() {
	    	@Override
	        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
	            PreparedStatement ps =
	                connection.prepareStatement(INSERT_SQL, new String[] {"id"});
	            ps.setInt(1, userId);
	            ps.setLong(2, money);
	            ps.setDate(3, new Date(System.currentTimeMillis()));
	            return ps;
	        }
	    },
	    keyHolder);
	
	return keyHolder.getKey().intValue();
}
 
Example 4
Project: wherehowsX   File: PatternDao.java   Source Code and License 6 votes vote down vote up
public static int insertLogLineagePattern(JsonNode logLineagePattern) throws Exception {
  Map<String, Object> params = new HashMap<>();
  params.put("regex", JsonUtil.getJsonValue(logLineagePattern, "regex", String.class));
  params.put("databaseType", JsonUtil.getJsonValue(logLineagePattern, "database_type", String.class));
  params.put("operationType", JsonUtil.getJsonValue(logLineagePattern, "operation_type", String.class));
  params.put("patternType", JsonUtil.getJsonValue(logLineagePattern, "pattern_type", String.class, null));
  params.put("sourceTargetType", JsonUtil.getJsonValue(logLineagePattern, "source_target_type", String.class, null));
  params.put("databaseNameIndex", JsonUtil.getJsonValue(logLineagePattern, "database_name_index", Integer.class, null));
  params.put("datasetIndex", JsonUtil.getJsonValue(logLineagePattern, "dataset_index", Integer.class, null));
  params.put("recordCountIndex", JsonUtil.getJsonValue(logLineagePattern, "record_count_index", Integer.class, null));
  params.put("recordByteIndex", JsonUtil.getJsonValue(logLineagePattern, "record_byte_index", Integer.class, null));
  params.put("insertCountIndex", JsonUtil.getJsonValue(logLineagePattern, "insert_count_index", Integer.class, null));
  params.put("insertByteIndex", JsonUtil.getJsonValue(logLineagePattern, "insert_byte_index", Integer.class, null));
  params.put("deleteCountIndex", JsonUtil.getJsonValue(logLineagePattern, "delete_count_index", Integer.class, null));
  params.put("deleteByteIndex", JsonUtil.getJsonValue(logLineagePattern, "delete_byte_index", Integer.class, null));
  params.put("updateCountIndex", JsonUtil.getJsonValue(logLineagePattern, "update_count_index", Integer.class, null));
  params.put("updateByteIndex", JsonUtil.getJsonValue(logLineagePattern, "update_byte_index", Integer.class, null));
  params.put("comments", JsonUtil.getJsonValue(logLineagePattern, "comments", String.class, null));

  KeyHolder kh = JdbcUtil.insertRow(INSERT_LOG_LINEAGE_PATTERN, params);
  return kh.getKey().intValue();
}
 
Example 5
Project: wherehowsX   File: EtlJobPropertyDao.java   Source Code and License 6 votes vote down vote up
public static int insertJobProperty(EtlJobName etlJobName, Integer refId, String propertyName, String propertyValue,
  boolean isEncrypted)
  throws Exception {
  Map<String, Object> params = new HashMap<>();
  params.put("etlJobName", etlJobName.toString());
  params.put("refId", refId);
  params.put("refIdType", etlJobName.getRefIdType().toString());
  params.put("propertyName", propertyName);
  if (isEncrypted) {
    params.put("propertyValue", encrypt(propertyValue));
    params.put("isEncrypted", "Y");
  } else {
    params.put("propertyValue", propertyValue);
    params.put("isEncrypted", "N");
  }
  KeyHolder kh = JdbcUtil.insertRow(INSERT_JOB_PROPERTY, params);
  return kh.getKey().intValue();
}
 
Example 6
Project: wherehowsX   File: EtlJobPropertyDao.java   Source Code and License 6 votes vote down vote up
public static int insertWherehowsProperty(String propertyName, String propertyValue, boolean isEncrypted,
  String groupName)
  throws Exception {
  Map<String, Object> params = new HashMap<>();
  params.put("propertyName", propertyName);
  params.put("propertyValue", propertyValue);
  if (isEncrypted) {
    params.put("propertyValue", encrypt(propertyValue));
    params.put("isEncrypted", "Y");
  } else {
    params.put("propertyValue", propertyValue);
    params.put("isEncrypted", "N");
  }
  params.put("groupName", groupName);
  KeyHolder kh = JdbcUtil.insertRow(INSERT_WHEREHOWS_PROPERTY, params);
  return kh.getKey().intValue();
}
 
Example 7
Project: common-dao   File: InsertSupport.java   Source Code and License 6 votes vote down vote up
public void insertSelective(Object record){
    try {
        Entity entity=getEntity(record.getClass());
        final Set<Entity.Column> insertColumn = getNotNullColumn(record, entity);
        final StringBuilder sql = new StringBuilder();
        sql.append(SqlHelper.insertIntoTable(entity.getTableName()));
        sql.append(SqlHelper.insertColumns(record, insertColumn));
        System.out.println(sql.toString());
        KeyHolder holder=new GeneratedKeyHolder();
        jdbcTemplate.update(sql.toString(), getParameterMap(record, insertColumn,false), holder, new String[]{entity.getPrimaryKey().getName()});
        int primaryKeyValue = holder.getKey().intValue();
        entity.getPrimaryKey().getField().set(record, primaryKeyValue);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 8
Project: multitenancybymycat   File: UserDao.java   Source Code and License 6 votes vote down vote up
@Transactional
public User create(String tenantSchema, final User user) {
	final String sql = MessageFormat.format(TENANT_SQL_TEMPLATE, tenantSchema, "insert into user(name,password) values(?,?)");

	KeyHolder holder = new GeneratedKeyHolder();

	jdbcTemplate.update(new PreparedStatementCreator() {

		@Override
		public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
			PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			ps.setString(1, user.getName());
			ps.setString(2, user.getPassword());
			return ps;
		}
	}, holder);

	int newUserId = holder.getKey().intValue();
	user.setId(newUserId);
	return user;
}
 
Example 9
Project: nixmash-blog   File: GithubJobUI.java   Source Code and License 6 votes vote down vote up
public long getCurrentGithubId() {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    String sql = "SELECT stat_id FROM github_stats WHERE stat_date = current_date()";
    long statId = -1;
    try {
        statId = jdbcTemplate.queryForObject(sql, Long.class);
    } catch (EmptyResultDataAccessException e) {

        jdbcTemplate.update(
                new PreparedStatementCreator() {
                    String INSERT_SQL = "INSERT INTO github_stats (stat_date) VALUES (current_date())";
                    public PreparedStatement createPreparedStatement(Connection cn) throws SQLException {
                        PreparedStatement ps = cn.prepareStatement(INSERT_SQL, new String[] {"stat_id"});
                        return ps;
                    }
                },
                keyHolder);
        statId = keyHolder.getKey().longValue();

    }
    logger.info("Current GitHub Stats ID: " + statId);
    return statId;
}
 
Example 10
Project: nixmash-blog   File: GitHubTests.java   Source Code and License 6 votes vote down vote up
@Test
public void githubStatRecordKeyReturned() throws Exception {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    long statId = -1L;
    try {
        statId = jdbcTemplate.queryForObject("SELECT stat_id FROM github_stats WHERE stat_date = '2010-10-10'", Long.class);
    } catch (EmptyResultDataAccessException e) {

        jdbcTemplate.update(
                new PreparedStatementCreator() {
                    String INSERT_SQL = "INSERT INTO github_stats (stat_date) VALUES ('2010-10-10')";

                    public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                        PreparedStatement ps = connection.prepareStatement(INSERT_SQL, new String[]{"stat_id"});
                        return ps;
                    }
                },
                keyHolder);
        statId = keyHolder.getKey().longValue();
    }

    assertThat(statId).isGreaterThan(0);
}
 
Example 11
Project: idea-forge   File: IdeaRepository.java   Source Code and License 6 votes vote down vote up
public Idea insert(Idea idea, User currentUser) {
	String sql = "insert into idea (title, description, user_id) values (?,?,?)";
	KeyHolder keyHolder = new GeneratedKeyHolder();
	jdbcTemplate.update(new PreparedStatementCreator() {
		@Override
		public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
			PreparedStatement ps = connection.prepareStatement(sql, new String[] { "id" });
			ps.setString(1, idea.getTitle());
			ps.setString(2, idea.getDescription());
			ps.setLong(3, currentUser.getId());
			return ps;
		}
	}, keyHolder);
	idea.setId(keyHolder.getKey().longValue());
	return idea;
}
 
Example 12
Project: graphium   File: WayGraphVersionMetadataDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
@Transactional(readOnly=false)
public long saveGraph(String graphName) {
	Object[] args = new Object[1];
	args[0] = graphName;
	
	Map<String, Object>  params = new HashMap<String, Object>(); 
	params.put("name", graphName);
	MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource(params);
	KeyHolder keyHolder = new GeneratedKeyHolder();

	getNamedParameterJdbcTemplate().update("INSERT INTO " + schema + "waygraphs (name) VALUES (:name)", 
			sqlParameterSource, keyHolder, new String[] {"id"});

	return Long.class.cast(keyHolder.getKey());
}
 
Example 13
Project: lams   File: NamedParameterJdbcTemplate.java   Source Code and License 6 votes vote down vote up
@Override
public int update(
		String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder, String[] keyColumnNames)
		throws DataAccessException {

	ParsedSql parsedSql = getParsedSql(sql);
	String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource);
	Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, null);
	List<SqlParameter> declaredParameters = NamedParameterUtils.buildSqlParameterList(parsedSql, paramSource);
	PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory(sqlToUse, declaredParameters);
	if (keyColumnNames != null) {
		pscf.setGeneratedKeysColumnNames(keyColumnNames);
	}
	else {
		pscf.setReturnGeneratedKeys(true);
	}
	return getJdbcOperations().update(pscf.newPreparedStatementCreator(params), generatedKeyHolder);
}
 
Example 14
Project: nh-micro   File: MicroMetaDao.java   Source Code and License 6 votes vote down vote up
public int insertObj(final String sql,final Object[] paramArray, KeyHolder keyHolder, final String idCol) {

		JdbcTemplate jdbcTemplate =getMicroJdbcTemplate();
		logger.debug(sql);
		logger.debug(Arrays.toString(paramArray));
		Integer retStatus=jdbcTemplate.update(new PreparedStatementCreator() { 

			public PreparedStatement createPreparedStatement(Connection con) 
			throws SQLException { 
					String[] keyColNames=new String[1];
					keyColNames[0]=idCol;
					PreparedStatement ps=con.prepareStatement(sql,keyColNames); 
					if(paramArray!=null){
						int size=paramArray.length;
						for(int i=0;i<size;i++){
							ps.setObject(i+1, paramArray[i]);
						}
					}
		
					return ps; 
				} 
			}, keyHolder);	
		return retStatus;
	}
 
Example 15
Project: lorne_mysql   File: BaseJdbcTemplate.java   Source Code and License 6 votes vote down vote up
public Long insertAndGetKey(final String sql, final Object... args) {
    final String mSql = initSql(sql);
    KeyHolder keyHolder = new GeneratedKeyHolder();
    getJdbcTemplate().update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(mSql, Statement.RETURN_GENERATED_KEYS);
            if (args != null && args.length > 0) {
                for (int index = 0; index < args.length; index++) {
                    ps.setObject((index + 1), args[index]);
                }
            }
            return ps;
        }
    }, keyHolder);
    Long generatedId = keyHolder.getKey().longValue();
    return generatedId;
}
 
Example 16
Project: keti   File: V2_0_1__InitializeIdentityZones.java   Source Code and License 6 votes vote down vote up
private Long createDefaultAuthzZone(final JdbcTemplate jdbcTemplate) {
    final String insertZoneSql =
            "INSERT INTO authorization_zone (name, description, subdomain) " + "VALUES (?,?,?)";
    KeyHolder holder = new GeneratedKeyHolder();

    jdbcTemplate.update(new PreparedStatementCreator() {

        @Override
        public PreparedStatement createPreparedStatement(final Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(insertZoneSql, new String[] { "id" });
            ps.setString(1, "apm-migrated");
            ps.setString(2, "APM Migrated Zone from mvp1");
            ps.setString(3, "apm-migrated");
            return ps;
        }
    }, holder);

    return holder.getKey().longValue();
}
 
Example 17
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 18
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 19
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 20
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 21
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 22
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 23
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 24
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 25
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 26
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 27
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 28
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 29
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 30
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 31
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 32
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 33
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 34
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 35
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 36
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 37
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 38
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 39
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 40
Project: Spring-Security-Third-Edition   File: JdbcCalendarUserDao.java   Source Code and License 6 votes vote down vote up
@Override
public int createUser(final CalendarUser userToAdd) {
    if (userToAdd == null) {
        throw new IllegalArgumentException("userToAdd cannot be null");
    }
    if (userToAdd.getId() != null) {
        throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setString(1, userToAdd.getEmail());
            ps.setString(2, userToAdd.getPassword());
            ps.setString(3, userToAdd.getFirstName());
            ps.setString(4, userToAdd.getLastName());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 41
Project: spring-jdbc-orm   File: SupportJdbcRepository.java   Source Code and License 6 votes vote down vote up
/**
 * 保存
 *
 * @param sql              sql
 * @param autoGeneratedKey 是否从数据库生成自增长的key, false则返回成功记录数
 * @param params           参数
 *
 * @return 主键对应的值
 */
protected Serializable insert(String sql, boolean autoGeneratedKey, Object... params) {

    PreparedStatementCreator psc = new PreparedStatementCreator(sql, autoGeneratedKey, params);
    return jdbcTemplate.execute(psc, new PreparedStatementCallback<Serializable>() {
        @Override
        public Serializable doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            if (autoGeneratedKey) {
                KeyHolder keyHolder = GenerationType.AUTO.generation(ps, 1);
                if (null != keyHolder) {
                    return keyHolder.getKey();
                }
            }
            return psc.getRowCont();
        }
    });
}
 
Example 42
Project: services-in-one   File: V1_1__initial_data.java   Source Code and License 6 votes vote down vote up
private int createAddress(final JdbcTemplate jdbcTemplate, final String address1, final String address2, final String city, final String country, final String region, final String zip) throws SQLException {
    // insert the address
    final KeyHolder keyHolder = new GeneratedKeyHolder();
    final Timestamp now = Timestamp.valueOf(ZonedDateTime.now().toLocalDateTime());
    final int version = 0;
    final int i = jdbcTemplate.update(c -> {
        final PreparedStatement statement = c.prepareStatement(SQL_INSERT_ADDRESS, new String[]{"id"});
        statement.setObject(1, now);
        statement.setObject(2, now);
        statement.setInt(3, version);
        statement.setString(4, address1);
        statement.setString(5, address2);
        statement.setString(6, city);
        statement.setString(7, country);
        statement.setString(8, region);
        statement.setString(9, zip);
        return statement;
    }, keyHolder);
    final int id = keyHolder.getKey().intValue();
    log.info("Inserted {} address entry: id={}, created_date={}, last_modified_date={}, version={}, address_1={}, address_2={}, city={}, country={}, region={}, zip_code={}", i, id, now, now, version, address1, address2, city, country, region, zip);
    return id;
}
 
Example 43
Project: services-in-one   File: V1_1__initial_data.java   Source Code and License 6 votes vote down vote up
private int createDetails(final JdbcTemplate jdbcTemplate, final String firstName, final String email, final int addressId, final String institution, final String abbreviation, final String url, final String jobTitle, final String lastName, final String phone) throws SQLException {
    // insert the userDetails
    final KeyHolder keyHolder = new GeneratedKeyHolder();
    final Timestamp now = Timestamp.valueOf(ZonedDateTime.now().toLocalDateTime());
    final int version = 0;
    final int i = jdbcTemplate.update(c -> {
        final PreparedStatement statement = c.prepareStatement(SQL_INSERT_USERS_DETAILS, new String[]{"id"});
        statement.setObject(1, now);
        statement.setObject(2, now);
        statement.setInt(3, version);
        statement.setString(4, email);
        statement.setString(5, firstName);
        statement.setString(6, institution);
        statement.setString(7, abbreviation);
        statement.setString(8, url);
        statement.setString(9, jobTitle);
        statement.setString(10, lastName);
        statement.setString(11, phone);
        statement.setInt(12, addressId);
        return statement;
    }, keyHolder);
    final int id = keyHolder.getKey().intValue();
    log.info("Insert {} details entry: id={}, created_date={}, last_modified_date={}, version={}, email={}, first_name={}, institution={}, institution_abbreviation={}, institution_web={}, job_title={}, last_name={}, phone={}, address_id={}", i, id, now, now, version, email, firstName, institution, abbreviation, url, jobTitle, lastName, phone, addressId);
    return id;
}
 
Example 44
Project: services-in-one   File: V1_13__set_category_for_existing_datasets.java   Source Code and License 6 votes vote down vote up
private int createCategory(final JdbcTemplate jdbcTemplate, final String name, final String description) {
    final KeyHolder keyHolder = new GeneratedKeyHolder();
    final Timestamp now = Timestamp.valueOf(ZonedDateTime.now().toLocalDateTime());
    final int version = 0;
    final int i = jdbcTemplate.update(c -> {
        final PreparedStatement statement = c.prepareStatement(SQL_INSERT_CATEGORY, new String[]{"id"});
        statement.setObject(1, now);
        statement.setObject(2, now);
        statement.setInt(3, version);
        statement.setString(4, name);
        statement.setString(5, description);
        return statement;
    }, keyHolder);
    final int id = keyHolder.getKey().intValue();
    log.info("Inserted {} category entry: id={}, created_date={}, last_modified_date={}, version={}, name={}, description={}", i, id, now, now, version, name, description);
    return id;
}
 
Example 45
Project: services-in-one   File: V1_15__insert_data_licenses.java   Source Code and License 6 votes vote down vote up
private int createLicense(final JdbcTemplate jdbcTemplate,
                          final String name,
                          final String acronym,
                          final String description,
                          final String link) {
    final KeyHolder keyHolder = new GeneratedKeyHolder();
    final Timestamp now = Timestamp.valueOf(ZonedDateTime.now().toLocalDateTime());
    final int version = 0;
    final int i = jdbcTemplate.update(c -> {
        final PreparedStatement statement = c.prepareStatement(SQL_INSERT_LICENSE, new String[]{"id"});
        statement.setObject(1, now);
        statement.setObject(2, now);
        statement.setInt(3, version);
        statement.setString(4, name);
        statement.setString(5, acronym);
        statement.setString(6, description);
        statement.setString(7, link);
        return statement;
    }, keyHolder);
    final int id = keyHolder.getKey().intValue();
    log.info("Inserted {} category entry: id={}, created_date={}, last_modified_date={}, version={}, name={}, description={}",
             i, id, now, now, version, name, description);
    return id;
}
 
Example 46
Project: metacat   File: MySqlTagService.java   Source Code and License 6 votes vote down vote up
/**
 * findOrCreateTagItemByName.
 *
 * @param name name to find or create
 * @return Tag Item
 * @throws SQLException sql exception
 */
private TagItem findOrCreateTagItemByName(final String name) throws SQLException {
    TagItem result = get(name);
    if (result == null) {
        final KeyHolder holder = new GeneratedKeyHolder();
        jdbcTemplate.update(connection -> {
            final PreparedStatement ps = connection.prepareStatement(SQL_INSERT_TAG_ITEM,
                Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, name);
            ps.setString(2, config.getTagServiceUserAdmin());
            ps.setString(3, config.getTagServiceUserAdmin());
            return ps;
        }, holder);
        final Long id = holder.getKey().longValue();
        result = new TagItem();
        result.setName(name);
        result.setId(id);
    }
    return result;
}
 
Example 47
Project: metacat   File: MySqlLookupService.java   Source Code and License 6 votes vote down vote up
/**
 * findOrCreateLookupByName.
 *
 * @param name name to find or create
 * @return Look up object
 * @throws SQLException sql exception
 */
private Lookup findOrCreateLookupByName(final String name) throws SQLException {
    Lookup lookup = get(name);
    if (lookup == null) {
        final KeyHolder holder = new GeneratedKeyHolder();
        jdbcTemplate.update(connection -> {
            final PreparedStatement ps = connection.prepareStatement(SQL_INSERT_LOOKUP,
                Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, name);
            ps.setString(2, STRING_TYPE);
            ps.setString(3, config.getLookupServiceUserAdmin());
            ps.setString(4, config.getLookupServiceUserAdmin());
            return ps;
        }, holder);
        final Long lookupId = holder.getKey().longValue();
        lookup = new Lookup();
        lookup.setName(name);
        lookup.setId(lookupId);
    }
    return lookup;
}
 
Example 48
Project: SpringMvcBlog   File: PostDaoImpl.java   Source Code and License 6 votes vote down vote up
public boolean saveVisitorAndComment(final Comment comment){

		jdbcTemplate = new JdbcTemplate(dataSource);
		
		final String sql = "INSERT INTO visitors(VisitorName,Email) VALUES(?,?)";
		
		KeyHolder keyHolder = new GeneratedKeyHolder();
		
		int result = jdbcTemplate.update( new PreparedStatementCreator() {
	        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
	            PreparedStatement pst = con.prepareStatement(sql, new String[] {"Id"});
	            pst.setString(1, comment.getName());
	            pst.setString(2, comment.getEmail());
	            return pst;
	        }
	    }, keyHolder);
		
		final Long lastId = (Long)keyHolder.getKey();
		
		if(result != 0){
			comment.setCommentatorId(lastId.intValue());
			return saveVisitor(comment);
		} else {
			return false;
		}
	}
 
Example 49
Project: spring4-understanding   File: NamedParameterJdbcTemplate.java   Source Code and License 6 votes vote down vote up
@Override
public int update(
		String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder, String[] keyColumnNames)
		throws DataAccessException {

	ParsedSql parsedSql = getParsedSql(sql);
	String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource);
	Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, null);
	List<SqlParameter> declaredParameters = NamedParameterUtils.buildSqlParameterList(parsedSql, paramSource);
	PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory(sqlToUse, declaredParameters);
	if (keyColumnNames != null) {
		pscf.setGeneratedKeysColumnNames(keyColumnNames);
	}
	else {
		pscf.setReturnGeneratedKeys(true);
	}
	return getJdbcOperations().update(pscf.newPreparedStatementCreator(params), generatedKeyHolder);
}
 
Example 50
Project: spring4-understanding   File: SqlUpdateTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testUpdateAndGeneratedKeys() throws SQLException {
	given(resultSetMetaData.getColumnCount()).willReturn(1);
	given(resultSetMetaData.getColumnLabel(1)).willReturn("1");
	given(resultSet.getMetaData()).willReturn(resultSetMetaData);
	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getObject(1)).willReturn(11);
	given(preparedStatement.executeUpdate()).willReturn(1);
	given(preparedStatement.getGeneratedKeys()).willReturn(resultSet);
	given(connection.prepareStatement(INSERT_GENERATE_KEYS,
			PreparedStatement.RETURN_GENERATED_KEYS)
		).willReturn(preparedStatement);

	GeneratedKeysUpdater pc = new GeneratedKeysUpdater();
	KeyHolder generatedKeyHolder = new GeneratedKeyHolder();
	int rowsAffected = pc.run("rod", generatedKeyHolder);

	assertEquals(1, rowsAffected);
	assertEquals(1, generatedKeyHolder.getKeyList().size());
	assertEquals(11, generatedKeyHolder.getKey().intValue());
	verify(preparedStatement).setString(1, "rod");
	verify(resultSet).close();
}
 
Example 51
Project: vidsell-data-simulator   File: DbSellingOrderDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
public long save(DbSellingOrder o) {
	KeyHolder keyHolder = new GeneratedKeyHolder();
	jdbcTpl.update(con -> {
		PreparedStatement ps = con.prepareStatement(SQL_insert, Statement.RETURN_GENERATED_KEYS);
		ps.setString(1, o.getProductId());
		ps.setLong(2, o.getCustomerId());
		ps.setDate(3, new Date(o.getOrderDate().getTime()));
		ps.setInt(4, o.getQuantity());
		ps.setLong(5, o.getRevenue());
		ps.setFloat(6, o.getDiscount());
		return ps;
	}, keyHolder);
	long id = keyHolder.getKey().longValue();
	return id;
}
 
Example 52
Project: vidsell-data-simulator   File: DbUserDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
public long save(DbUser u) {
	long id = getIdByEmail(u.getEmail());
	if(id == 0){
		KeyHolder keyHolder = new GeneratedKeyHolder();
		jdbcTpl.update(con -> {
			PreparedStatement ps = con.prepareStatement(SQL_insert, Statement.RETURN_GENERATED_KEYS);

			ps.setString(1, u.getName());
			ps.setString(2, u.getEmail());
			ps.setInt(3, u.getAge());
			ps.setInt(4, u.getGender());
			ps.setString(5, u.getLocation());
			ps.setDate(6, new Date(u.getCreationDate().getTime()));
			ps.setDate(7, new Date(u.getModification().getTime()));

			return ps;
		}, keyHolder);
		id = keyHolder.getKey().longValue();

	}
	return id;
}
 
Example 53
Project: vidsell-data-simulator   File: DbVideoDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
public String save(DbVideo v) {
	KeyHolder keyHolder = new GeneratedKeyHolder();
	int n = 0;
	try {
		n = jdbcTpl.update(con -> {
			PreparedStatement ps = con.prepareStatement(SQL_insert, Statement.RETURN_GENERATED_KEYS);

			ps.setString(1, v.getVideo_id());
			ps.setString(2, v.getUrl() );
			ps.setString(3, v.getCategory());
			ps.setString(4, v.getTitle());
			ps.setString(5, v.getDescription());
			ps.setString(6, v.getThumbnailImage());			
			ps.setTimestamp(7, new Timestamp(v.getPublishedTime().getTime()) );
			ps.setString(8, v.getChannelId());
			ps.setString(9, v.getChannelTitle());
			ps.setString(10, v.getProductId());			

			return ps;
		}, keyHolder);
	} catch (Exception e) {}

	return n > 0 ? v.getVideo_id() : "";
}
 
Example 54
Project: osmp   File: BaseTemplate.java   Source Code and License 6 votes vote down vote up
@Override
public long insert(Map<String,Object> paramMap, String sql) {
    logger.debug("Insert sql : \n" + sql);
    logger.debug("Paramters : \n" + paramMap);
    try {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        this.ownJdbcTemplate.getJdbcOperations().update(getPreparedStatementCreator(sql,paramMap), keyHolder);
        if(keyHolder.getKey() == null) {
            return -1;
        }
        return keyHolder.getKey().longValue();
    } catch (DataAccessException ex) {
        logger.error(ex.getMessage(), ex);
        throw ex;
    }
}
 
Example 55
Project: nh-micro   File: MicroMetaDao.java   Source Code and License 6 votes vote down vote up
public int insertObj(final String sql,final Object[] paramArray, KeyHolder keyHolder, final String idCol) {

		JdbcTemplate jdbcTemplate =getMicroJdbcTemplate();
		logger.debug(sql);
		logger.debug(Arrays.toString(paramArray));
		Integer retStatus=jdbcTemplate.update(new PreparedStatementCreator() { 

			public PreparedStatement createPreparedStatement(Connection con) 
			throws SQLException { 
					String[] keyColNames=new String[1];
					keyColNames[0]=idCol;
					PreparedStatement ps=con.prepareStatement(sql,keyColNames); 
					if(paramArray!=null){
						int size=paramArray.length;
						for(int i=0;i<size;i++){
							ps.setObject(i+1, paramArray[i]);
						}
					}
		
					return ps; 
				} 
			}, keyHolder);	
		return retStatus;
	}
 
Example 56
Project: tcc-transaction   File: TradeOrderRepository.java   Source Code and License 6 votes vote down vote up
public void insert(TradeOrder tradeOrder) {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(new PreparedStatementCreator() {
        @Override
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement stmt = connection.prepareStatement("insert into red_trade_order(self_user_id,opposite_user_id,merchant_order_no,amount,status) values(?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
            stmt.setObject(1, tradeOrder.getSelfUserId());
            stmt.setObject(2, tradeOrder.getOppositeUserId());
            stmt.setObject(3, tradeOrder.getMerchantOrderNo());
            stmt.setObject(4, tradeOrder.getAmount());
            stmt.setObject(5, tradeOrder.getStatus());
            return stmt;
        }
    }, keyHolder);
    tradeOrder.setId(keyHolder.getKey().longValue());
}
 
Example 57
Project: nbone   File: NamedJdbcDao.java   Source Code and License 6 votes vote down vote up
@Override
public Serializable save(Object object) {
	SqlModel<Object> sqlModel = sqlBuilder.insertSelectiveSql(object);
	checkSqlModel(sqlModel);
	
	SqlParameterSource paramSource =  new BeanPropertySqlParameterSource(object);
	KeyHolder generatedKeyHolder =  new  GeneratedKeyHolder();
	namedPjdbcTemplate.update(sqlModel.getSql(), paramSource, generatedKeyHolder);
	return generatedKeyHolder.getKey();
}
 
Example 58
Project: duke-programming-contest   File: GroupService.java   Source Code and License 6 votes vote down vote up
private void createGroupAndInsertUserSQL(String name, String secret, String contestId, long userId) {
    final String INSERT_SQL =
            "INSERT INTO groups (group_name, secret, contest_id) VALUES (?, ?, ?)";

    KeyHolder keyHolder = new GeneratedKeyHolder();
    jt.update(
            connection -> {
                PreparedStatement ps = connection.prepareStatement(INSERT_SQL, new String[]{"group_id"});
                ps.setString(1, name);
                ps.setString(2, secret);
                ps.setString(3, contestId);
                return ps;
            },
            keyHolder);
    long groupId = keyHolder.getKey().longValue();

    joinGroupSQL(groupId, userId);
}
 
Example 59
Project: duke-programming-contest   File: AuthService.java   Source Code and License 6 votes vote down vote up
private long createUser(String email, String name, String passhash, String school, String classInSchool) {
    final String INSERT_SQL =
            "INSERT INTO users (email, name, passhash, school, class_in_school) " +
                    "VALUES (?, ?, ?, ?, ?)";

    KeyHolder keyHolder = new GeneratedKeyHolder();
    jt.update(
            connection -> {
                PreparedStatement ps = connection.prepareStatement(INSERT_SQL, new String[]{"user_id"});
                ps.setString(1, email);
                ps.setString(2, name);
                ps.setString(3, passhash);
                ps.setString(4, school);
                ps.setString(5, classInSchool);
                return ps;
            },
            keyHolder);
    return keyHolder.getKey().longValue();
}
 
Example 60
Project: dazzle   File: SpringDaoUtils.java   Source Code and License 6 votes vote down vote up
/**@author [email protected]*/
public static final Long insert(
		JdbcOperations jdbcOperations, 
		final String sql,
		final List<Object> params) {
	KeyHolder keyHolder = new GeneratedKeyHolder();
	try {
		Logger.getLogger("org.dazzle.util").debug("sql ==>" + sql.toString());
		Logger.getLogger("org.dazzle.util").debug("args==>" + params);
		jdbcOperations.update(
				new PreparedStatementCreator() {
					@Override
					public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
						PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
						setParams(ps, params);
						return ps;
					}
				}, keyHolder);
		if(null != keyHolder.getKey()) {
			return keyHolder.getKey().longValue();
		}
	} catch (RuntimeException e) {
		catchException(e);
	}
	return null;
}