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

The following are top voted examples for showing how to use org.springframework.jdbc.support.GeneratedKeyHolder. 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: appframework   File: UserDaoJdbcImpl.java   Source Code and License 7 votes vote down vote up
@Override
public Long insertUser(User u) {
	StringBuffer sql = new StringBuffer("");
	sql.append(" insert into user ");
	sql.append(" ( username, password ) ");
	sql.append(" values ( ");
	sql.append("   :username ");
	sql.append(" , :password ");
	sql.append(" ) ");
	
	SqlParameterSource paramSource = new BeanPropertySqlParameterSource(u);
	KeyHolder generatedKeyHolder = new GeneratedKeyHolder();
	int rows = getDao().update(sql.toString(), paramSource, generatedKeyHolder);
	
	if(rows > 0 ){
		Long userId = generatedKeyHolder.getKey().longValue();
		u.setId(userId);
	}
	
	return u.getId();
}
 
Example 4
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 5
Project: spring-data-jdbc   File: BaseJdbcRepository.java   Source Code and License 6 votes vote down vote up
private <S extends T> S insertWithAutoGeneratedKey(S entity, Map<String, Object> columns) {
    removeIdColumns(columns);

    final String insertQuery = sqlGenerator.insert(table, columns);
    final Object[] queryParams = columns.values().toArray();
    final GeneratedKeyHolder key = new GeneratedKeyHolder();

    jdbcOps.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            String idColumnName = table.getPkColumns().get(0);
            PreparedStatement ps = con.prepareStatement(insertQuery, new String[]{idColumnName});
            for (int i = 0; i < queryParams.length; ++i) {
                ps.setObject(i + 1, queryParams[i]);
            }
            return ps;
        }
    }, key);

    return postInsert(entity, key.getKey());
}
 
Example 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
Project: nakadi-producer-spring-boot-starter   File: EventLogRepositoryImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void persist(EventLog eventLog) {
    Timestamp now = toSqlTimestamp(Instant.now());
    MapSqlParameterSource namedParameterMap = new MapSqlParameterSource();
    namedParameterMap.addValue("eventType", eventLog.getEventType());
    namedParameterMap.addValue("eventBodyData", eventLog.getEventBodyData());
    namedParameterMap.addValue("flowId", eventLog.getFlowId());
    namedParameterMap.addValue("created", now);
    namedParameterMap.addValue("lastModified", now);
    namedParameterMap.addValue("lockedBy", eventLog.getLockedBy());
    namedParameterMap.addValue("lockedUntil", eventLog.getLockedUntil());
    GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(
        "INSERT INTO " +
            "    nakadi_events.event_log " +
            "    (event_type, event_body_data, flow_id, created, last_modified, locked_by, locked_until) " +
            "VALUES " +
            "    (:eventType, :eventBodyData, :flowId, :created, :lastModified, :lockedBy, :lockedUntil)",
        namedParameterMap,
        generatedKeyHolder
    );

    eventLog.setId((Integer) generatedKeyHolder.getKeys().get("id"));
}
 
Example 15
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 16
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 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: 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 40
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 41
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 42
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 43
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 44
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 45
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 46
Project: shiro-demo   File: PermissionDaoImpl.java   Source Code and License 6 votes vote down vote up
public Permission createPermission(final Permission permission) {
    final String sql = "insert into sys_permissions(permission, description, available) values(?,?,?)";

    GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement psst = connection.prepareStatement(sql,  new String[] { "id" });
            psst.setString(1, permission.getPermission());
            psst.setString(2, permission.getDescription());
            psst.setBoolean(3, permission.getAvailable());
            return psst;
        }
    }, keyHolder);
    permission.setId(keyHolder.getKey().longValue());
    return permission;
}
 
Example 47
Project: shiro-demo   File: RoleDaoImpl.java   Source Code and License 6 votes vote down vote up
public Role createRole(final Role role) {
    final String sql = "insert into sys_roles(role, description, available) values(?,?,?)";

    GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement psst = connection.prepareStatement(sql, new String[] { "id" });
            psst.setString(1, role.getRole());
            psst.setString(2, role.getDescription());
            psst.setBoolean(3, role.getAvailable());
            return psst;
        }
    }, keyHolder);
    role.setId(keyHolder.getKey().longValue());

    return role;
}
 
Example 48
Project: shiro-demo   File: UserDaoImpl.java   Source Code and License 6 votes vote down vote up
public User createUser(final User user) {
    final String sql = "insert into sys_users(username, password, salt, locked) values(?,?,?, ?)";

    GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement psst = connection.prepareStatement(sql, new String[] { "id" });
            psst.setString(1, user.getUsername());
            psst.setString(2, user.getPassword());
            psst.setString(3, user.getSalt());
            psst.setBoolean(4, user.getLocked());
            return psst;
        }
    }, keyHolder);

    user.setId(keyHolder.getKey().longValue());
    return user;
}
 
Example 49
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 50
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 51
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 52
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 53
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 54
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 55
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 56
Project: oauth_demo   File: ClientDaoImpl.java   Source Code and License 6 votes vote down vote up
public Client createClient(final Client client) {
    final String sql = "insert into oauth2_client(client_name, client_id, client_secret) values(?,?,?)";

    GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(new PreparedStatementCreator() {
        @Override
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement psst = connection.prepareStatement(sql, new String[]{"id"});
            int count = 1;
            psst.setString(count++, client.getClientName());
            psst.setString(count++, client.getClientId());
            psst.setString(count++, client.getClientSecret());
            return psst;
        }
    }, keyHolder);

    client.setId(keyHolder.getKey().longValue());
    return client;
}
 
Example 57
Project: oauth_demo   File: UserDaoImpl.java   Source Code and License 6 votes vote down vote up
public User createUser(final User user) {
    final String sql = "insert into oauth2_user(username, password, salt) values(?,?,?)";

    GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(new PreparedStatementCreator() {
        @Override
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement psst = connection.prepareStatement(sql, new String[]{"id"});
            int count = 1;
            psst.setString(count++, user.getUsername());
            psst.setString(count++, user.getPassword());
            psst.setString(count++, user.getSalt());
            return psst;
        }
    }, keyHolder);

    user.setId(keyHolder.getKey().longValue());
    return user;
}
 
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;
}