當前位置: 首頁>>代碼示例>>Java>>正文


Java GeneratedKeyHolder類代碼示例

本文整理匯總了Java中org.springframework.jdbc.support.GeneratedKeyHolder的典型用法代碼示例。如果您正苦於以下問題:Java GeneratedKeyHolder類的具體用法?Java GeneratedKeyHolder怎麽用?Java GeneratedKeyHolder使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


GeneratedKeyHolder類屬於org.springframework.jdbc.support包,在下文中一共展示了GeneratedKeyHolder類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: add

import org.springframework.jdbc.support.GeneratedKeyHolder; //導入依賴的package包/類
@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;
}
 
開發者ID:thinking-github,項目名稱:nbone,代碼行數:19,代碼來源:NamedJdbcDao.java

示例2: testInsert

import org.springframework.jdbc.support.GeneratedKeyHolder; //導入依賴的package包/類
@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");
    
}
 
開發者ID:mybatis,項目名稱:mybatis-dynamic-sql,代碼行數:26,代碼來源:SpringTest.java

示例3: insertUser

import org.springframework.jdbc.support.GeneratedKeyHolder; //導入依賴的package包/類
@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();
}
 
開發者ID:jiucai,項目名稱:appframework,代碼行數:22,代碼來源:UserDaoJdbcImpl.java

示例4: saveOrderRecord

import org.springframework.jdbc.support.GeneratedKeyHolder; //導入依賴的package包/類
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();
}
 
開發者ID:QNJR-GROUP,項目名稱:EasyTransaction,代碼行數:21,代碼來源:OrderService.java

示例5: insertWithAutoGeneratedKey

import org.springframework.jdbc.support.GeneratedKeyHolder; //導入依賴的package包/類
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());
}
 
開發者ID:rubasace,項目名稱:spring-data-jdbc,代碼行數:21,代碼來源:BaseJdbcRepository.java

示例6: insertSelective

import org.springframework.jdbc.support.GeneratedKeyHolder; //導入依賴的package包/類
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();
    }
}
 
開發者ID:ChenAt,項目名稱:common-dao,代碼行數:17,代碼來源:InsertSupport.java

示例7: create

import org.springframework.jdbc.support.GeneratedKeyHolder; //導入依賴的package包/類
@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;
}
 
開發者ID:tangaiyun,項目名稱:multitenancybymycat,代碼行數:22,代碼來源:UserDao.java

示例8: getCurrentGithubId

import org.springframework.jdbc.support.GeneratedKeyHolder; //導入依賴的package包/類
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;
}
 
開發者ID:mintster,項目名稱:nixmash-blog,代碼行數:24,代碼來源:GithubJobUI.java

示例9: githubStatRecordKeyReturned

import org.springframework.jdbc.support.GeneratedKeyHolder; //導入依賴的package包/類
@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);
}
 
開發者ID:mintster,項目名稱:nixmash-blog,代碼行數:24,代碼來源:GitHubTests.java

示例10: insert

import org.springframework.jdbc.support.GeneratedKeyHolder; //導入依賴的package包/類
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;
}
 
開發者ID:garydamm,項目名稱:idea-forge,代碼行數:17,代碼來源:IdeaRepository.java

示例11: saveGraph

import org.springframework.jdbc.support.GeneratedKeyHolder; //導入依賴的package包/類
@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());
}
 
開發者ID:graphium-project,項目名稱:graphium,代碼行數:17,代碼來源:WayGraphVersionMetadataDaoImpl.java

示例12: insertAndGetKey

import org.springframework.jdbc.support.GeneratedKeyHolder; //導入依賴的package包/類
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;
}
 
開發者ID:1991wangliang,項目名稱:lorne_mysql,代碼行數:18,代碼來源:BaseJdbcTemplate.java

示例13: createDefaultAuthzZone

import org.springframework.jdbc.support.GeneratedKeyHolder; //導入依賴的package包/類
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();
}
 
開發者ID:eclipse,項目名稱:keti,代碼行數:20,代碼來源:V2_0_1__InitializeIdentityZones.java

示例14: persist

import org.springframework.jdbc.support.GeneratedKeyHolder; //導入依賴的package包/類
@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"));
}
 
開發者ID:zalando-nakadi,項目名稱:nakadi-producer-spring-boot-starter,代碼行數:25,代碼來源:EventLogRepositoryImpl.java

示例15: createUser

import org.springframework.jdbc.support.GeneratedKeyHolder; //導入依賴的package包/類
@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();
}
 
開發者ID:PacktPublishing,項目名稱:Spring-Security-Third-Edition,代碼行數:24,代碼來源:JdbcCalendarUserDao.java


注:本文中的org.springframework.jdbc.support.GeneratedKeyHolder類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。