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

The following examples show how to use org.springframework.jdbc.core.simple.SimpleJdbcInsert. 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 File: DbInsert.java    From yue-library with 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 #2
Source File: RideRepositoryImpl.java    From Spring with 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 #3
Source File: V20190406_1__MigrateBugRelation.java    From mycollab with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #4
Source File: DbInsert.java    From yue-library with 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 #5
Source File: SimpleJdbcLockTest.java    From distributed-lock with 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 #6
Source File: JdbcSchedulerExecutionRepository.java    From spring-batch-lightmin with Apache License 2.0 5 votes vote down vote up
public JdbcSchedulerExecutionRepository(final JdbcTemplate jdbcTemplate,
                                        final ServerSchedulerJdbcConfigurationProperties properties) throws Exception {
    this.jdbcTemplate = jdbcTemplate;
    this.simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate)
            .withSchemaName(properties.getDatabaseSchema())
            .withTableName(properties.getExecutionTable())
            .usingGeneratedKeyColumns(SchedulerExecutionDomain.ID);
    this.tableName = properties.getExecutionTable();
    this.rowMapper = new SchedulerExecutionRowMapper();
    this.byStatePagingQueryProvider = this.getPagingQueryProvider("S.state = ?");
    this.findAllPagingQueryProvider = this.getPagingQueryProvider(null);
}
 
Example #7
Source File: JdbcVisitRepositoryImpl.java    From audit4j-demo with Apache License 2.0 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 #8
Source File: JdbcOwnerRepositoryImpl.java    From audit4j-demo with Apache License 2.0 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 #9
Source File: JdbcPetRepositoryImpl.java    From audit4j-demo with Apache License 2.0 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 #10
Source File: TaskStartTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
private void enableLock(String lockKey) {
	SimpleJdbcInsert taskLockInsert = new SimpleJdbcInsert(this.dataSource)
			.withTableName("TASK_LOCK");
	Map<String, Object> taskLockParams = new HashMap<>();
	taskLockParams.put("LOCK_KEY",
			UUID.nameUUIDFromBytes(lockKey.getBytes()).toString());
	taskLockParams.put("REGION", "DEFAULT");
	taskLockParams.put("CLIENT_ID", "aClientID");
	taskLockParams.put("CREATED_DATE", new Date());
	taskLockInsert.execute(taskLockParams);
}
 
Example #11
Source File: SpringJDBCTemplateExample.java    From java-course-ee with MIT License 5 votes vote down vote up
private static void insertConstructor(JdbcTemplate jdbc) {
    separator("insertConstructor");
    SimpleJdbcInsert insertActor = new SimpleJdbcInsert(jdbc).withSchemaName("region").withTableName("jc_region").usingGeneratedKeyColumns("region_id");

    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("region_name", "new region name");
    Number number = insertActor.executeAndReturnKey(parameters);
    log.debug("Inserted region id: {}", number.longValue());
}
 
Example #12
Source File: SimpleJdbcLockTest.java    From distributed-lock with 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 #13
Source File: JdbcJobConfigurationRepository.java    From spring-batch-lightmin with Apache License 2.0 5 votes vote down vote up
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 #14
Source File: SimpleJdbcLockTest.java    From distributed-lock with 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 #15
Source File: JdbcSpittleRepository.java    From Project with 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 #16
Source File: EmployeeDAO.java    From tutorials with MIT License 5 votes vote down vote up
@Autowired
public void setDataSource(final DataSource dataSource) {
    jdbcTemplate = new JdbcTemplate(dataSource);
    final CustomSQLErrorCodeTranslator customSQLErrorCodeTranslator = new CustomSQLErrorCodeTranslator();
    jdbcTemplate.setExceptionTranslator(customSQLErrorCodeTranslator);

    namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
    simpleJdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("EMPLOYEE");
    
    // Commented as the database is H2, change the database and create procedure READ_EMPLOYEE before calling getEmployeeUsingSimpleJdbcCall 
    //simpleJdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("READ_EMPLOYEE");
}
 
Example #17
Source File: JdbcOrderRepository.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@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 #18
Source File: JdbcSchedulerConfigurationRepository.java    From spring-batch-lightmin with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #19
Source File: DbInsert.java    From yue-library with 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 #20
Source File: JdbcJobConfigurationRepository.java    From spring-batch-lightmin with Apache License 2.0 5 votes vote down vote up
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 #21
Source File: JdbcPetRepositoryImpl.java    From docker-workflow-plugin with 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
Source File: JdbcVisitRepositoryImpl.java    From DevOps-for-Web-Development with 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 #23
Source File: JdbcOwnerRepositoryImpl.java    From docker-workflow-plugin with 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 #24
Source File: JdbcPetRepositoryImpl.java    From DevOps-for-Web-Development with 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 #25
Source File: JdbcVisitRepositoryImpl.java    From DevOps-for-Web-Development with MIT License 5 votes vote down vote up
@Autowired
public JdbcVisitRepositoryImpl(DataSource dataSource) {
    this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

    this.insertVisit = new SimpleJdbcInsert(dataSource)
        .withTableName("visits")
        .usingGeneratedKeyColumns("id");
}
 
Example #26
Source File: JdbcVisitRepositoryImpl.java    From docker-workflow-plugin with 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 #27
Source File: JdbcPetRepositoryImpl.java    From DevOps-for-Web-Development with 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
Source File: JDBCDataRepositoryImpl.java    From java-persistence-frameworks-comparison with MIT License 5 votes vote down vote up
@SuppressWarnings("SpringJavaAutowiringInspection")
@Autowired
public JDBCDataRepositoryImpl(NamedParameterJdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
    this.insertIntoProject = new SimpleJdbcInsert((JdbcTemplate) jdbcTemplate.getJdbcOperations())
            .withTableName("project")
            .usingGeneratedKeyColumns("pid");
}
 
Example #29
Source File: JdbcAuditRepository.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public JdbcAuditRepository(
    JdbcTemplate jdbcTemplate,
    ObjectMapper jsonMapper )
{
    this.jdbcTemplate = jdbcTemplate;
    this.jsonMapper = jsonMapper;

    this.auditInsert = new SimpleJdbcInsert( jdbcTemplate )
        .withTableName( "audit" )
        .usingGeneratedKeyColumns( "auditid" );
}
 
Example #30
Source File: SimpleJdbcClinic.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@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");
}