Java Code Examples for org.springframework.jdbc.core.simple.SimpleJdbcInsert

The following examples show how to use org.springframework.jdbc.core.simple.SimpleJdbcInsert. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: yue-library   Source File: DbInsert.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 插入源初始化
 * 
 * @param tableName
 * @param paramJson
 * @return
 */
private SimpleJdbcInsert insertInit(String tableName, JSONObject paramJson) {
	// 1. 参数验证
	paramValidate(tableName, paramJson);
	
	// 2. 创建JdbcInsert实例
	SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate);
	simpleJdbcInsert.setTableName(tableName); // 设置表名
	simpleJdbcInsert.setGeneratedKeyName(DbConstant.PRIMARY_KEY);	// 设置主键名,添加成功后返回主键的值
	
	// 3. 设置ColumnNames
	List<String> keys = MapUtils.keyList(paramJson);
	List<String> columnNames = ListUtils.toList(getMetaData(tableName).getColumnNames());
	List<String> insertColumn = ListUtils.keepSameValue(keys, (List<String>) dialect.getWrapper().wrap(columnNames));
	simpleJdbcInsert.setColumnNames(insertColumn);
	
	// 4. 返回结果
	return simpleJdbcInsert;
}
 
Example 2
Source Project: yue-library   Source File: DbInsert.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 向表中批量插入数据,主键默认为id时使用。
 * 
 * @param tableName 表名
 * @param paramJsons 参数
 */
@Transactional
public void insertBatch(String tableName, JSONObject[] paramJsons) {
	// 1. 参数验证
	paramValidate(tableName, paramJsons);
	
	// 2. 插入源初始化
	tableName = dialect.getWrapper().wrap(tableName);
	paramJsons = dialect.getWrapper().wrap(paramJsons);
	SimpleJdbcInsert simpleJdbcInsert = insertInit(tableName, paramJsons[0]);
	
	// 3. 执行
       int updateRowsNumber = simpleJdbcInsert.executeBatch(paramJsons).length;
       
       // 4. 确认插入条数
       if (updateRowsNumber != paramJsons.length) {
       	throw new DbException(ResultPrompt.INSERT_BATCH_ERROR);
       }
}
 
Example 3
Source Project: Spring   Source File: RideRepositoryImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Alternative to RideRepositoryImpl#createRide(com.pluralsight.model.Ride)
 */
public Ride createRideSimpleJDBC(Ride ride) {
	final SimpleJdbcInsert insert = new SimpleJdbcInsert(jdbcTemplate);

	insert.setGeneratedKeyName("id");

	final Map<String, Object> data = new HashMap<>();
	data.put("name", ride.getName());
	data.put("duration", ride.getDuration());

	final List<String> columns = new ArrayList<>();
	columns.add("name");
	columns.add("duration");

	insert.setTableName("ride");
	insert.setColumnNames(columns);

	final Number id = insert.executeAndReturnKey(data);
	return getRide(id);
}
 
Example 4
public void migrate(Context context) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(context.getConnection(), true));
    SimpleJdbcInsert insertOp = new SimpleJdbcInsert(jdbcTemplate).withTableName("m_prj_ticket_relation");

    List<Map<String, Object>> rows = jdbcTemplate.queryForList("SELECT * FROM m_tracker_related_bug");
    rows.forEach(row -> {
        Map<String, Object> parameters = new HashMap<>(6);
        parameters.put("ticketId", row.get("bugid"));
        parameters.put("ticketType", "Project-Bug");
        parameters.put("type", "Project-Bug");
        parameters.put("typeId", row.get("relatedid"));
        parameters.put("rel", row.get("relatetype"));
        parameters.put("comment", row.get("comment"));
        insertOp.execute(parameters);
    });
    jdbcTemplate.execute("DROP TABLE `m_tracker_related_bug`;");
}
 
Example 5
Source Project: yue-library   Source File: DbInsert.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 向表中插入一条数据,主键默认为id时使用。
 * 
 * @param tableName 表名
 * @param paramJson 参数
 * @return 返回主键值
 */
@Transactional
public Long insert(String tableName, JSONObject paramJson) {
	// 1. 移除空对象
	MapUtils.removeEmpty(paramJson);
	
	// 2. 插入源初始化
	tableName = dialect.getWrapper().wrap(tableName);
	paramJson = dialect.getWrapper().wrap(paramJson);
	SimpleJdbcInsert simpleJdbcInsert = insertInit(tableName, paramJson);
	
	// 3. 执行
	return simpleJdbcInsert.executeAndReturnKey(paramJson).longValue();
}
 
Example 6
Source Project: yue-library   Source File: DbInsert.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 向表中插入一条数据
 * 
 * @param tableName 表名
 * @param paramJson 参数
 */
@Transactional
public void insertNotReturn(String tableName, JSONObject paramJson) {
	// 1. 移除空对象
	MapUtils.removeEmpty(paramJson);
	
	// 2. 插入源初始化
	tableName = dialect.getWrapper().wrap(tableName);
	paramJson = dialect.getWrapper().wrap(paramJson);
	SimpleJdbcInsert simpleJdbcInsert = insertInit(tableName, paramJson);
	
	// 3. 执行
	simpleJdbcInsert.execute(paramJson);
}
 
Example 7
/**
 * Creates the employee in the database and returns the id of the created employee.
 * The method uses SimpleJdbcInsert instead of JdbcTemplate.
 * @param employee the employee to be created
 * @return the id of the created employee
 */
public long simpleSave(Employee employee) {
  SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate)
          .withTableName("employees")
          .usingGeneratedKeyColumns("id");

  return simpleJdbcInsert.executeAndReturnKey(employee.toMap()).longValue();
}
 
Example 8
Source Project: hedera-mirror-node   Source File: ConnectionHandler.java    License: Apache License 2.0 5 votes vote down vote up
public void insertTopicMessage(int newTopicsMessageCount, long topicNum, Instant startTime, long seqStart) {
    if (newTopicsMessageCount <= 0) {
        // no messages to create, abort and db logic
        return;
    }

    createTopic(topicNum);

    long nextSequenceNum = seqStart == -1 ? getNextAvailableSequenceNumber(topicNum) : seqStart;
    log.info("Inserting {} topic messages starting from sequence number {} and time {}", newTopicsMessageCount,
            nextSequenceNum, startTime);

    List<SqlParameterSource> parameterSources = new ArrayList<>();
    SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate.getDataSource())
            .withTableName("topic_message");

    for (int i = 1; i <= newTopicsMessageCount; i++) {
        long sequenceNum = nextSequenceNum + i;
        Instant consensusInstant = startTime.plusNanos(sequenceNum);
        TopicMessage topicMessage = TopicMessage.builder()
                .consensusTimestamp(consensusInstant)
                .sequenceNumber(sequenceNum)
                .message(BYTES)
                .runningHash(BYTES)
                .realmNum(0)
                .build();
        parameterSources.add(new BeanPropertySqlParameterSource(topicMessage));

        if (i % BATCH_SIZE == 0) {
            simpleJdbcInsert.executeBatch(parameterSources.toArray(new SqlParameterSource[] {}));
            parameterSources.clear();
        }
    }

    if (!parameterSources.isEmpty()) {
        simpleJdbcInsert.executeBatch(parameterSources.toArray(new SqlParameterSource[] {}));
    }

    log.debug("Successfully inserted {} topic messages", newTopicsMessageCount);
}
 
Example 9
@Autowired
public JdbcPetRepositoryImpl(DataSource dataSource, OwnerRepository ownerRepository,
        VisitRepository visitRepository) {
    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

    this.insertPet = new SimpleJdbcInsert(dataSource).withTableName("pets").usingGeneratedKeyColumns("id");

    this.ownerRepository = ownerRepository;
    this.visitRepository = visitRepository;
}
 
Example 10
Source Project: Project   Source File: JdbcSpitterRepository.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Inserts a spitter using SimpleJdbcInsert. 
 * Involves no direct SQL and is able to return the ID of the newly created Spitter.
 * @param spitter a Spitter to insert into the databse
 * @return the ID of the newly inserted Spitter
 */
private long insertSpitterAndReturnId(Spitter spitter) {
	SimpleJdbcInsert jdbcInsert = new SimpleJdbcInsert(jdbcTemplate).withTableName("Spitter");
	jdbcInsert.setGeneratedKeyName("id");
	Map<String, Object> args = new HashMap<String, Object>();
	args.put("username", spitter.getUsername());
	args.put("password", spitter.getPassword());
	args.put("fullname", spitter.getFullName());
	args.put("email", spitter.getEmail());
	args.put("updateByEmail", spitter.isUpdateByEmail());
	long spitterId = jdbcInsert.executeAndReturnKey(args).longValue();
	return spitterId;
}
 
Example 11
Source Project: Project   Source File: JdbcSpittleRepository.java    License: Apache License 2.0 5 votes vote down vote up
private long insertSpittleAndReturnId(Spittle spittle) {
		SimpleJdbcInsert jdbcInsert = new SimpleJdbcInsert(jdbcTemplate).withTableName("Spittle");
		jdbcInsert.setGeneratedKeyName("id");
		Map<String, Object> args = new HashMap<String, Object>();
		args.put("spitter", spittle.getSpitter().getId());
		args.put("message", spittle.getMessage());
		args.put("postedTime", spittle.getPostedTime());
		long spittleId = jdbcInsert.executeAndReturnKey(args).longValue();
		return spittleId;
}
 
Example 12
Source Project: Project   Source File: JdbcSpitterRepository.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Inserts a spitter using SimpleJdbcInsert. 
 * Involves no direct SQL and is able to return the ID of the newly created Spitter.
 * @param spitter a Spitter to insert into the databse
 * @return the ID of the newly inserted Spitter
 */
private long insertSpitterAndReturnId(Spitter spitter) {
	SimpleJdbcInsert jdbcInsert = new SimpleJdbcInsert(jdbcTemplate).withTableName("Spitter");
	jdbcInsert.setGeneratedKeyName("id");
	Map<String, Object> args = new HashMap<String, Object>();
	args.put("username", spitter.getUsername());
	args.put("password", spitter.getPassword());
	args.put("fullname", spitter.getFullName());
	args.put("email", spitter.getEmail());
	args.put("updateByEmail", spitter.isUpdateByEmail());
	long spitterId = jdbcInsert.executeAndReturnKey(args).longValue();
	return spitterId;
}
 
Example 13
Source Project: Project   Source File: JdbcSpittleRepository.java    License: Apache License 2.0 5 votes vote down vote up
private long insertSpittleAndReturnId(Spittle spittle) {
		SimpleJdbcInsert jdbcInsert = new SimpleJdbcInsert(jdbcTemplate).withTableName("Spittle");
		jdbcInsert.setGeneratedKeyName("id");
		Map<String, Object> args = new HashMap<String, Object>();
		args.put("spitter", spittle.getSpitter().getId());
		args.put("message", spittle.getMessage());
		args.put("postedTime", spittle.getPostedTime());
		long spittleId = jdbcInsert.executeAndReturnKey(args).longValue();
		return spittleId;
}
 
Example 14
@Autowired
public JdbcOrderRepository(JdbcTemplate jdbc) {
  this.orderInserter = new SimpleJdbcInsert(jdbc)
      .withTableName("Taco_Order")
      .usingGeneratedKeyColumns("id");

  this.orderTacoInserter = new SimpleJdbcInsert(jdbc)
      .withTableName("Taco_Order_Tacos");

  this.objectMapper = new ObjectMapper();
}
 
Example 15
Source Project: distributed-lock   Source File: SimpleJdbcLockTest.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldNotLock() {
  new SimpleJdbcInsert(jdbcTemplate)
    .withTableName("locks")
    .usingGeneratedKeyColumns("id")
    .executeAndReturnKey(values("1", "def"));

  final var token = lock.acquire(Collections.singletonList("1"), "locks", 1000);
  assertThat(token).isNull();

  final var acquiredLockMap = jdbcTemplate.queryForObject("SELECT * FROM locks WHERE id = 1", new ColumnMapRowMapper());
  assertThat(acquiredLockMap).containsAllEntriesOf(values("1", "def"));
}
 
Example 16
Source Project: distributed-lock   Source File: SimpleJdbcLockTest.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldRelease() {
  new SimpleJdbcInsert(jdbcTemplate)
    .withTableName("locks")
    .usingGeneratedKeyColumns("id")
    .executeAndReturnKey(values("1", "abc"));

  final var released = lock.release(Collections.singletonList("1"), "locks", "abc");
  assertThat(released).isTrue();
  assertThat(jdbcTemplate.queryForList("SELECT * FROM locks")).isNullOrEmpty();
}
 
Example 17
Source Project: distributed-lock   Source File: SimpleJdbcLockTest.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldNotRelease() {
  new SimpleJdbcInsert(jdbcTemplate)
    .withTableName("locks")
    .usingGeneratedKeyColumns("id")
    .executeAndReturnKey(values("1", "def"));

  lock.release(Collections.singletonList("1"), "locks", "abc");

  final var acquiredLockMap = jdbcTemplate.queryForObject("SELECT * FROM locks WHERE id = 1", new ColumnMapRowMapper());
  assertThat(acquiredLockMap).containsAllEntriesOf(values("1", "def"));
}
 
Example 18
@Autowired
public JdbcVisitRepositoryImpl(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);

    this.insertVisit = new SimpleJdbcInsert(dataSource)
        .withTableName("visits")
        .usingGeneratedKeyColumns("id");
}
 
Example 19
Source Project: DevOps-for-Web-Development   Source File: JdbcPetRepositoryImpl.java    License: MIT License 5 votes vote down vote up
@Autowired
public JdbcPetRepositoryImpl(DataSource dataSource, OwnerRepository ownerRepository, VisitRepository visitRepository) {
    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

    this.insertPet = new SimpleJdbcInsert(dataSource)
        .withTableName("pets")
        .usingGeneratedKeyColumns("id");

    this.ownerRepository = ownerRepository;
    this.visitRepository = visitRepository;
}
 
Example 20
@Autowired
public JdbcVisitRepositoryImpl(DataSource dataSource) {
    this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

    this.insertVisit = new SimpleJdbcInsert(dataSource)
        .withTableName("visits")
        .usingGeneratedKeyColumns("id");
}
 
Example 21
Source Project: DevOps-for-Web-Development   Source File: JdbcPetRepositoryImpl.java    License: MIT License 5 votes vote down vote up
@Autowired
public JdbcPetRepositoryImpl(DataSource dataSource, OwnerRepository ownerRepository, VisitRepository visitRepository) {
    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

    this.insertPet = new SimpleJdbcInsert(dataSource)
        .withTableName("pets")
        .usingGeneratedKeyColumns("id");

    this.ownerRepository = ownerRepository;
    this.visitRepository = visitRepository;
}
 
Example 22
@SuppressWarnings("SpringJavaAutowiringInspection")
@Autowired
public JDBCDataRepositoryImpl(NamedParameterJdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
    this.insertIntoProject = new SimpleJdbcInsert((JdbcTemplate) jdbcTemplate.getJdbcOperations())
            .withTableName("project")
            .usingGeneratedKeyColumns("pid");
}
 
Example 23
public JdbcAuditRepository(
    JdbcTemplate jdbcTemplate,
    ObjectMapper jsonMapper )
{
    this.jdbcTemplate = jdbcTemplate;
    this.jsonMapper = jsonMapper;

    this.auditInsert = new SimpleJdbcInsert( jdbcTemplate )
        .withTableName( "audit" )
        .usingGeneratedKeyColumns( "auditid" );
}
 
Example 24
@Autowired
public void init(DataSource dataSource) {
	this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);

	this.insertOwner = new SimpleJdbcInsert(dataSource)
		.withTableName("owners")
		.usingGeneratedKeyColumns("id");
	this.insertPet = new SimpleJdbcInsert(dataSource)
		.withTableName("pets")
		.usingGeneratedKeyColumns("id");
	this.insertVisit = new SimpleJdbcInsert(dataSource)
		.withTableName("visits")
		.usingGeneratedKeyColumns("id");
}
 
Example 25
Source Project: docker-workflow-plugin   Source File: JdbcVisitRepositoryImpl.java    License: MIT License 5 votes vote down vote up
@Autowired
public JdbcVisitRepositoryImpl(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);

    this.insertVisit = new SimpleJdbcInsert(dataSource)
            .withTableName("visits")
            .usingGeneratedKeyColumns("id");
}
 
Example 26
Source Project: docker-workflow-plugin   Source File: JdbcOwnerRepositoryImpl.java    License: MIT License 5 votes vote down vote up
@Autowired
public JdbcOwnerRepositoryImpl(DataSource dataSource, NamedParameterJdbcTemplate namedParameterJdbcTemplate,
                               VisitRepository visitRepository) {

    this.insertOwner = new SimpleJdbcInsert(dataSource)
            .withTableName("owners")
            .usingGeneratedKeyColumns("id");

    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

    this.visitRepository = visitRepository;
}
 
Example 27
Source Project: docker-workflow-plugin   Source File: JdbcPetRepositoryImpl.java    License: MIT License 5 votes vote down vote up
@Autowired
public JdbcPetRepositoryImpl(DataSource dataSource, OwnerRepository ownerRepository, VisitRepository visitRepository) {
    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

    this.insertPet = new SimpleJdbcInsert(dataSource)
            .withTableName("pets")
            .usingGeneratedKeyColumns("id");

    this.ownerRepository = ownerRepository;
    this.visitRepository = visitRepository;
}
 
Example 28
JobConfigurationDAO(final JdbcTemplate jdbcTemplate, final String tableName, final String schema) {
    this.jdbcTemplate = jdbcTemplate;
    this.tableName = tableName;
    this.simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate)
            .withSchemaName(schema)
            .withTableName(String.format(TABLE_NAME, tableName)).usingGeneratedKeyColumns(
                    JobConfigurationDomain.JOB_CONFIGURATION_ID);
    final JobConfigurationRowMapper jobConfigurationRowMapper = new JobConfigurationRowMapper();
    this.jobConfigurationJdbcWrapperRowMapper = new JobConfigurationJdbcWrapperRowMapper(jobConfigurationRowMapper);
}
 
Example 29
JobConfigurationParameterDAO(final JdbcTemplate jdbcTemplate, final String tableName, final String schema) {
    this.jdbcTemplate = jdbcTemplate;
    this.tableName = tableName;
    this.simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate)
            .withSchemaName(schema)
            .withTableName(String.format(TABLE_NAME, tableName))
            .usingGeneratedKeyColumns(JobConfigurationParameterDomain.ID);
    this.dateFormat = new SimpleDateFormat(DomainParameterParser.DATE_FORMAT_WITH_TIMESTAMP);
}
 
Example 30
private SchedulerConfigurationDAO(final JdbcTemplate jdbcTemplate,
                                  final String tableName,
                                  final SchedulerConfigurationValueDAO schedulerConfigurationValueDAO,
                                  final String schema) throws Exception {
    this.jdbcTemplate = jdbcTemplate;
    this.simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate)
            .withTableName(tableName)
            .withSchemaName(schema)
            .usingGeneratedKeyColumns(SchedulerConfigurationDomain.ID);
    this.tableName = tableName;
    this.schedulerConfigurationValueDAO = schedulerConfigurationValueDAO;
    this.rowMapper = new SchedulerConfigurationRowMapper();
    this.findAllPagingQueryProvider = this.getPagingQueryProvider(null);
}