Java Code Examples for org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource

The following examples show how to use org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource. 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: FastSQL   Source File: BaseDAO.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 批量插入
 */
public int[] batchInsert(List<E> entities) {

    StringBuilder nameBuilder = new StringBuilder();
    StringBuilder valueBuilder = new StringBuilder();
    fields.forEach(field -> {
        nameBuilder.append(",").append(StringExtUtils.camelToUnderline(field.getName()));
        valueBuilder.append(",:").append(field.getName());
    });


    String sql = getSQL()
            .INSERT_INTO(tableName, nameBuilder.deleteCharAt(0).toString())
            .VALUES(valueBuilder.deleteCharAt(0).toString()).build();

    SqlParameterSource[] sqlParameterSources = new BeanPropertySqlParameterSource[entities.size()];
    for (int i = 0; i < sqlParameterSources.length; i++) {
        sqlParameterSources[i] = new BeanPropertySqlParameterSource(entities.get(i));
    }

    return getSQL().getNamedParameterJdbcTemplate().batchUpdate(sql, sqlParameterSources);
}
 
Example 2
Source Project: FastSQL   Source File: BaseDAO.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 通过entity查找,不为空的值将会作为where条件
 */
public E selectOneByEntity(E entity) {
    String clause = " 1=1 ";
    for (Field field : fields) {
        Object fieldValue = EntityRefelectUtils.getFieldValue(entity, field);
        if (!StringUtils.isEmpty(fieldValue)){
            clause+=" AND "+StringExtUtils.camelToUnderline(field.getName())+" = :"+field.getName();
        }
    }

    E returnObject;
    try {
        returnObject = getSQL()
                .SELECT(columns)
                .FROM(tableName)
                .WHERE(clause)
                .parameter(new BeanPropertySqlParameterSource(entity))
                .queryOne(entityClass);
    } catch (EmptyResultDataAccessException e) {
        returnObject = null;
    }
    return returnObject;
}
 
Example 3
Source Project: maven-framework-project   Source File: PGAlertDao.java    License: MIT License 6 votes vote down vote up
@Override
@Transactional
public String create(Alert alert) {
    log.debug("Inserting alert into SQL backend: " + alert);
    checkArgument(StringUtils.isBlank(alert.getId()), "alert id cannot be already set");

    String id = UUID.randomUUID().toString();
    alert.setId(id);
    String sql = "INSERT INTO Alert (id, created_by, message, priority, user_id,  acknowledged, created_date) " +
            "VALUES (:id, :createdBy, :message, :priority, :userId, :acknowledged, :createdDate)";

    BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(alert);
    int results = this.namedJdbcTemplate.update(sql, source);
    log.debug("Got: " + results + " results");

    return id;
}
 
Example 4
Source Project: maven-framework-project   Source File: PGAlertDao.java    License: MIT License 6 votes vote down vote up
@Override
@Transactional(readOnly = true)
public List<Alert> readPage(PagingCriteria criteria) {
    log.debug("reading page with criteria: " + criteria);
    if (criteria == null || criteria.getLimit() == null || criteria.getStart() == null) {
        log.warn("criteria invalid - reading all instead of subset");
        return readAll();
    }
    String sql = "SELECT LIMIT :start :limit * FROM Alert ORDER BY created_date ASC";
    BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(criteria);

    List<Alert> alerts = this.namedJdbcTemplate.query(sql, source, new AlertRowMapper());
    log.debug(alerts.size() + " alerts returned using criteria: " + criteria);

    return alerts;
}
 
Example 5
Source Project: maven-framework-project   Source File: PGDocumentDao.java    License: MIT License 6 votes vote down vote up
@Override
@Transactional
public String create(Document document) {
    log.debug("Inserting Document into SQL backend: " + document);
    checkArgument(StringUtils.isBlank(document.getId()), "Document id cannot be already set");

    String id = UUID.randomUUID().toString();
    document.setId(id);
    String sql = "INSERT INTO Document (id, author, title, content, summary, group_id, state_, created_date) " +
            "VALUES (:id, :author, :title, :content, :summary, :groupId, :state, :createdDate)";

    BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(document);
    int results = this.namedJdbcTemplate.update(sql, source);
    log.debug("Got: " + results + " results");
    document.setId(id);
    return id;
}
 
Example 6
Source Project: maven-framework-project   Source File: PGDocumentDao.java    License: MIT License 6 votes vote down vote up
@Override
@Transactional(readOnly = true)
public List<Document> readPage(PagingCriteria criteria) {
    log.debug("reading page with criteria: " + criteria);
    if (criteria == null || criteria.getLimit() == null || criteria.getStart() == null) {
        log.warn("criteria invalid - reading all instead of subset");
        return readAll();
    }
    String sql = "SELECT LIMIT :start :limit * FROM Document ORDER BY created_date ASC";
    BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(criteria);

    List<Document> documents = this.namedJdbcTemplate.query(sql, source, new DocumentRowMapper());
    log.debug(documents.size() + " Documents returned using criteria: " + criteria);

    return documents;
}
 
Example 7
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 8
@Override
public void save(Owner owner) throws DataAccessException {
    BeanPropertySqlParameterSource parameterSource = new BeanPropertySqlParameterSource(owner);
    if (owner.isNew()) {
        Number newKey = this.insertOwner.executeAndReturnKey(parameterSource);
        owner.setId(newKey.intValue());
    } else {
        this.namedParameterJdbcTemplate
                .update("UPDATE owners SET first_name=:firstName, last_name=:lastName, address=:address, "
                        + "city=:city, telephone=:telephone WHERE id=:id", parameterSource);
    }
}
 
Example 9
Source Project: spring-init   Source File: JdbcFooRepository.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void save(Foo foo) {
	if (foo.getId() == null) {
		KeyHolder holder = new GeneratedKeyHolder();
		template.update("INSERT into foos (value) values (:value)",
				new BeanPropertySqlParameterSource(foo), holder);
		foo.setId(holder.getKey().longValue());
	}
	else {
		template.update("UPDATE foos set value=:value where id=:id",
				new BeanPropertySqlParameterSource(foo));
	}
}
 
Example 10
Source Project: SpringAll   Source File: SysLogDaoImp.java    License: MIT License 5 votes vote down vote up
@Override
public void saveSysLog(SysLog syslog) {
	StringBuffer sql = new StringBuffer("insert into sys_log ");
	sql.append("(id,username,operation,time,method,params,ip,create_time) ");
	sql.append("values(seq_sys_log.nextval,:username,:operation,:time,:method,");
	sql.append(":params,:ip,:createTime)");

	NamedParameterJdbcTemplate npjt = new NamedParameterJdbcTemplate(this.jdbcTemplate.getDataSource());
	npjt.update(sql.toString(), new BeanPropertySqlParameterSource(syslog));
}
 
Example 11
Source Project: SpringAll   Source File: StudentDaoImp.java    License: MIT License 5 votes vote down vote up
@Override
public int add(Student student) {
	// String sql = "insert into student(sno,sname,ssex) values(?,?,?)";
	// Object[] args = { student.getSno(), student.getName(), student.getSex() };
	// int[] argTypes = { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR };
	// return this.jdbcTemplate.update(sql, args, argTypes);
	String sql = "insert into student(sno,sname,ssex) values(:sno,:name,:sex)";
	NamedParameterJdbcTemplate npjt = new NamedParameterJdbcTemplate(this.jdbcTemplate.getDataSource());
	return npjt.update(sql, new BeanPropertySqlParameterSource(student));
}
 
Example 12
Source Project: maestro-java   Source File: EasyRunner.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Inserts a record in the DB
 * @param jdbcTemplate the Spring JDBC template object
 * @param query the query to run
 * @param bean the bean with the data to insert
 * @return the ID of the record updated
 */
public static int runInsert(final NamedParameterJdbcTemplate jdbcTemplate, final String query, final Object bean) {
    SqlParameterSource beanParameters = new BeanPropertySqlParameterSource(bean);
    KeyHolder keyHolder = new GeneratedKeyHolder();

    jdbcTemplate.update(query, beanParameters, keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 13
Source Project: FastSQL   Source File: BaseDAO.java    License: Apache License 2.0 5 votes vote down vote up
public List<E> selectByEntity(E entity) {
    String clause = " 1=1 ";
    for (Field field : fields) {
        Object fieldValue = EntityRefelectUtils.getFieldValue(entity, field);
        if (!StringUtils.isEmpty(fieldValue)){
            clause+=" AND "+StringExtUtils.camelToUnderline(field.getName())+" = :"+field.getName();
        }
    }

    return getSQL().SELECT(columns)
            .FROM(tableName)
            .WHERE(clause)
            .parameter(new BeanPropertySqlParameterSource(entity))
            .queryList(entityClass);
}
 
Example 14
@Override
public void save(Owner owner) throws DataAccessException {
    BeanPropertySqlParameterSource parameterSource = new BeanPropertySqlParameterSource(owner);
    if (owner.isNew()) {
        Number newKey = this.insertOwner.executeAndReturnKey(parameterSource);
        owner.setId(newKey.intValue());
    } else {
        this.namedParameterJdbcTemplate.update(
            "UPDATE owners SET first_name=:firstName, last_name=:lastName, address=:address, " +
                "city=:city, telephone=:telephone WHERE id=:id",
            parameterSource);
    }
}
 
Example 15
@Override
public void save(Owner owner) throws DataAccessException {
    BeanPropertySqlParameterSource parameterSource = new BeanPropertySqlParameterSource(owner);
    if (owner.isNew()) {
        Number newKey = this.insertOwner.executeAndReturnKey(parameterSource);
        owner.setId(newKey.intValue());
    } else {
        this.namedParameterJdbcTemplate.update(
            "UPDATE owners SET first_name=:firstName, last_name=:lastName, address=:address, " +
                "city=:city, telephone=:telephone WHERE id=:id",
            parameterSource);
    }
}
 
Example 16
@Transactional
public void storeOwner(Owner owner) throws DataAccessException {
	if (owner.isNew()) {
		Number newKey = this.insertOwner.executeAndReturnKey(
				new BeanPropertySqlParameterSource(owner));
		owner.setId(newKey.intValue());
	}
	else {
		this.simpleJdbcTemplate.update(
				"UPDATE owners SET first_name=:firstName, last_name=:lastName, address=:address, " +
				"city=:city, telephone=:telephone WHERE id=:id",
				new BeanPropertySqlParameterSource(owner));
	}
}
 
Example 17
Source Project: docker-workflow-plugin   Source File: JdbcOwnerRepositoryImpl.java    License: MIT License 5 votes vote down vote up
@Override
public void save(Owner owner) throws DataAccessException {
    BeanPropertySqlParameterSource parameterSource = new BeanPropertySqlParameterSource(owner);
    if (owner.isNew()) {
        Number newKey = this.insertOwner.executeAndReturnKey(parameterSource);
        owner.setId(newKey.intValue());
    } else {
        this.namedParameterJdbcTemplate.update(
                "UPDATE owners SET first_name=:firstName, last_name=:lastName, address=:address, " +
                        "city=:city, telephone=:telephone WHERE id=:id",
                parameterSource);
    }
}
 
Example 18
Source Project: audit4j-demo   Source File: JdbcOwnerRepositoryImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void save(Owner owner) throws DataAccessException {
    BeanPropertySqlParameterSource parameterSource = new BeanPropertySqlParameterSource(owner);
    if (owner.isNew()) {
        Number newKey = this.insertOwner.executeAndReturnKey(parameterSource);
        owner.setId(newKey.intValue());
    } else {
        this.namedParameterJdbcTemplate.update(
                "UPDATE owners SET first_name=:firstName, last_name=:lastName, address=:address, " +
                        "city=:city, telephone=:telephone WHERE id=:id",
                parameterSource);
    }
}
 
Example 19
Source Project: maven-framework-project   Source File: JdbcCustomerDAO.java    License: MIT License 5 votes vote down vote up
/**
 * 使用SimpleJdbcInsert和BeanPropertySqlParameterSource方式 新增数据
 * @param customer
 */
public void useBeanPropertySqlParameterSource(Customer customer){
	//封装BeanPropertySqlParameterSource
	SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(customer);
	//设置表名(withTableName)和设置自增长主键(usingGeneratedKeyColumns)
	Number key = simpleJdbcInsert.withTableName("CUSTOMER").usingGeneratedKeyColumns("CUST_ID").executeAndReturnKey(parameterSource);
	customer.setCustId(key.intValue());//返回新增后的主键
	System.out.println(customer.getCustId());
}
 
Example 20
Source Project: maven-framework-project   Source File: JdbcCustomerDAO.java    License: MIT License 5 votes vote down vote up
/**
 * 使用namedParameterJdbcTemplate和BeanPropertySqlParameterSource批量插入
 * @param customers
 */
public void insertBatchUseSqlParameterSource(final List<Customer> customers) {

	String sql = "INSERT INTO CUSTOMER " + "(NAME, AGE) VALUES (:name, :age)";

	List<SqlParameterSource> parameters = new ArrayList<SqlParameterSource>();
	for (Customer cust : customers) {
		parameters.add(new BeanPropertySqlParameterSource(cust));
	}

	namedParameterJdbcTemplate.batchUpdate(sql,parameters.toArray(new SqlParameterSource[0]));
}
 
Example 21
Source Project: maven-framework-project   Source File: PGAlertDao.java    License: MIT License 5 votes vote down vote up
@Override
@Transactional
public void update(Alert alert) {
    checkArgument(StringUtils.isNotBlank(alert.getId()), "alert id cannot be blank");
    String sql = "UPDATE Alert SET created_by=:createdBy, user_id=:userId, message=:message, priority=:priority," +
            " acknowledged=:acknowledged  WHERE id=:id";

    BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(alert);
    int results = this.namedJdbcTemplate.update(sql, source);
    log.debug("Updated: " + results + " alerts");
}
 
Example 22
Source Project: maven-framework-project   Source File: PGDocumentDao.java    License: MIT License 5 votes vote down vote up
@Override
@Transactional
public void update(Document document) {
    checkArgument(StringUtils.isNotBlank(document.getId()), "document id cannot be blank");
    String sql = "UPDATE Document SET author=:author, title=:title, content=:content, summary=:summary," +
            " group_Id=:groupId, state_=:state, created_date=:createdDate WHERE id=:id";

    BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(document);
    int results = this.namedJdbcTemplate.update(sql, source);
    log.debug("Updated: " + results + " Documents");
}
 
Example 23
Source Project: spring-boot   Source File: NamedParameterJdbcBookRepository.java    License: MIT License 4 votes vote down vote up
@Override
public int update(Book book) {
    return namedParameterJdbcTemplate.update(
            "update books set price = :price where id = :id",
            new BeanPropertySqlParameterSource(book));
}
 
Example 24
Source Project: jeewx   Source File: SimpleJdbcTemplate.java    License: Apache License 2.0 4 votes vote down vote up
protected BeanPropertySqlParameterSource paramBeanMapper(Object object) {
	return new BeanPropertySqlParameterSource(object);
}
 
Example 25
Source Project: jeecg   Source File: SimpleJdbcTemplate.java    License: Apache License 2.0 4 votes vote down vote up
protected BeanPropertySqlParameterSource paramBeanMapper(Object object) {
	return new BeanPropertySqlParameterSource(object);
}
 
Example 26
Source Project: tutorials   Source File: EmployeeDAO.java    License: MIT License 3 votes vote down vote up
public int getEmployeeUsingBeanPropertySqlParameterSource() {
    final Employee employee = new Employee();
    employee.setFirstName("James");

    final String SELECT_BY_ID = "SELECT COUNT(*) FROM EMPLOYEE WHERE FIRST_NAME = :firstName";

    final SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(employee);

    return namedParameterJdbcTemplate.queryForObject(SELECT_BY_ID, namedParameters, Integer.class);
}
 
Example 27
Source Project: maestro-java   Source File: EasyRunner.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Update records in the DB
 * @param jdbcTemplate the Spring JDBC template object
 * @param query the query to run
 * @param bean the bean with the data to update
 */
public static void runUpdate(final JdbcTemplate jdbcTemplate, final String query, final Object bean) {
    SqlParameterSource beanParameters = new BeanPropertySqlParameterSource(bean);

    jdbcTemplate.update(query, beanParameters);
}
 
Example 28
Source Project: maestro-java   Source File: EasyRunner.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Inserts a record in the DB
 * @param jdbcTemplate the Spring JDBC template object
 * @param query the query to run
 * @param bean the bean with the data to insert
 */
public static void runEmptyInsert(final NamedParameterJdbcTemplate jdbcTemplate, final String query, final Object bean) {
    SqlParameterSource beanParameters = new BeanPropertySqlParameterSource(bean);

    jdbcTemplate.update(query, beanParameters);
}