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

The following examples show how to use org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource. 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: PGAlertDao.java    From maven-framework-project with 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 #2
Source File: PGAlertDao.java    From maven-framework-project with MIT License 6 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 #3
Source File: PGAlertDao.java    From maven-framework-project with 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 File: JdbcCustomerDAO.java    From maven-framework-project with MIT License 6 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 #5
Source File: StudentDaoImp.java    From SpringAll with MIT License 6 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 #6
Source File: PGDocumentDao.java    From maven-framework-project with 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 File: BaseDAO.java    From FastSQL with 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 #8
Source File: BaseDAO.java    From FastSQL with 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 #9
Source File: PGDocumentDao.java    From maven-framework-project with 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 #10
Source File: BaseDAO.java    From FastSQL with 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 #11
Source File: JdbcCustomerDAO.java    From maven-framework-project with 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 #12
Source File: JdbcOwnerRepositoryImpl.java    From audit4j-demo with 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 #13
Source File: JdbcOwnerRepositoryImpl.java    From docker-workflow-plugin with 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 #14
Source File: SimpleJdbcClinic.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@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 #15
Source File: JdbcOwnerRepositoryImpl.java    From DevOps-for-Web-Development with 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 #16
Source File: JdbcOwnerRepositoryImpl.java    From DevOps-for-Web-Development with 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 #17
Source File: EasyRunner.java    From maestro-java with 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 #18
Source File: PGDocumentDao.java    From maven-framework-project with 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 #19
Source File: SysLogDaoImp.java    From SpringAll with 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 #20
Source File: JdbcFooRepository.java    From spring-init with 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 #21
Source File: JdbcOwnerRepositoryImpl.java    From spring-graalvm-native with 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 #22
Source File: ConnectionHandler.java    From hedera-mirror-node with 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 #23
Source File: SimpleJdbcTemplate.java    From jeecg with Apache License 2.0 4 votes vote down vote up
protected BeanPropertySqlParameterSource paramBeanMapper(Object object) {
	return new BeanPropertySqlParameterSource(object);
}
 
Example #24
Source File: SimpleJdbcTemplate.java    From jeewx with Apache License 2.0 4 votes vote down vote up
protected BeanPropertySqlParameterSource paramBeanMapper(Object object) {
	return new BeanPropertySqlParameterSource(object);
}
 
Example #25
Source File: NamedParameterJdbcBookRepository.java    From spring-boot with 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 #26
Source File: EmployeeDAO.java    From tutorials with 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 File: EasyRunner.java    From maestro-java with 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);
}
 
Example #28
Source File: EasyRunner.java    From maestro-java with 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);
}