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

The following are top voted examples for showing how to use org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: nbone   File: NamedJdbcDao.java   Source Code and License 8 votes vote down vote up
@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;
}
 
Example 2
Project: nbone   File: NamedJdbcDao.java   Source Code and License 7 votes vote down vote up
@Override
public int[] batchUpdate(Collection<?> objects) {
	SqlParameterSource[] batchArgs = new BeanPropertySqlParameterSource[objects.size()];
	String sql = null;
	int index = 0;
	for (Object object : objects) {
		if(index == 0 ){
			//XXX: thinking 共享第一实体的sql
			SqlModel<Object> sqlModel = sqlBuilder.updateSql(object);
			sql = sqlModel.getSql();
		}
		batchArgs[index] = new BeanPropertySqlParameterSource(object);
		
		index ++;
	}
	int[] rows = namedPjdbcTemplate.batchUpdate(sql, batchArgs);
	return rows;
}
 
Example 3
Project: mybatis-dynamic-sql   File: SpringTest.java   Source Code and License 7 votes vote down vote up
@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");
    
}
 
Example 4
Project: nics-common   File: ChatDAOImpl.java   Source Code and License 7 votes vote down vote up
public int addChat(Chat chat) throws Exception {
	List<String> fields = Arrays.asList(
		SADisplayConstants.CHAT_ID,	SADisplayConstants.COLLAB_ROOM_ID, SADisplayConstants.USER_ORG_ID,
		SADisplayConstants.CREATED, SADisplayConstants.SEQ_NUM, SADisplayConstants.MESSAGE);
		
	QueryModel model = QueryManager.createQuery(SADisplayConstants.CHAT_TABLE).insertInto(fields);
	
	//generate a chatid if not set
	if (chat.getChatid() <= 0) {
		QueryModel idModel = QueryManager.createQuery("chat_seq").selectNextVal();
		int id = this.template.queryForObject(idModel.toString(), new MapSqlParameterSource(), Integer.class);
		chat.setChatid(id);
	}
	
	try {
		this.template.update(model.toString(), new BeanPropertySqlParameterSource(chat));
		return chat.getChatid();
	} catch(Exception e) {
		throw new Exception("Unhandled exception while persisting Chat entity:", e);
	}
}
 
Example 5
Project: jersey-jax-rs-examples   File: EmployeeResource.java   Source Code and License 7 votes vote down vote up
@PUT
@Path("/{employeeId}")
public Employee editEmployee(final Employee employee, @PathParam("employeeId") Integer employeeId) {

	String sql = "update EMPLOYEE set name=:name, address=:address where id=:id";

	SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(employee);

	this.namedParameterJdbcTemplate.update(sql, namedParameters);

	sql = "select * from EMPLOYEE where id=:employeeId";
	SqlParameterSource namedParameters2 = new MapSqlParameterSource("employeeId", employeeId);
	return namedParameterJdbcTemplate.query(sql, namedParameters2, new EmployeeMapper()).get(0);
}
 
Example 6
Project: javase-study   File: QueryExampleHelper.java   Source Code and License 7 votes vote down vote up
/**
 * 根据主键创建查询条件
 *
 * @param pathBase Querydsl query type
 * @param pk       主键
 * @return 查询条件
 */
public static QueryExample createExampleByPk(RelationalPathBase<?> pathBase, Object pk) {
    int numOfPk = pathBase.getPrimaryKey().getLocalColumns().size();
    Validate.isTrue(numOfPk > 0, "primaryKey not exists");
    QueryExample example = QueryExample.newInstance();
    if (numOfPk == 1) {
        example.equalsTo(pathBase.getPrimaryKey().getLocalColumns()
                .get(0).getMetadata().getName(), pk);
    } else {
        SqlParameterSource source = new BeanPropertySqlParameterSource(pk);
        for (Path<?> path : pathBase.getPrimaryKey().getLocalColumns()) {
            String name = path.getMetadata().getName();
            String humpName = humpName(name);
            example.equalsTo(humpName, source.getValue(name));
        }
    }
    return example;
}
 
Example 7
Project: spring-xd-jdbc-job   File: JdbcTasklet.java   Source Code and License 7 votes vote down vote up
private String runCommand(StepContext steoContext, String sqlCommand) throws Exception {

		String msg = "";
		if (sqlCommand.trim().toUpperCase().startsWith("SELECT")) {
			logger.debug("Executing: " + sqlCommand);
			List<Map<String, Object>> result = jdbcTemplate.queryForList(sqlCommand,
					new BeanPropertySqlParameterSource(steoContext));
			msg = "Result: " + result;
			logger.debug(msg);
		} else {
			logger.debug("Updating : " + sqlCommand);
			int updated = jdbcTemplate.update(sqlCommand, new BeanPropertySqlParameterSource(steoContext));
			msg = "Updated: " + updated + " rows";
			logger.debug(msg);
		}

		return msg;
	}
 
Example 8
Project: maven-framework-project   File: PGAlertDao.java   Source Code and License 7 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 9
Project: maven-framework-project   File: PGAlertDao.java   Source Code and License 7 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 10
Project: maven-framework-project   File: PGDocumentDao.java   Source Code and License 7 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 11
Project: maven-framework-project   File: PGDocumentDao.java   Source Code and License 7 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 12
Project: oblatum   File: MappingJdbcTemplate.java   Source Code and License 7 votes vote down vote up
public <T> int delete(T t) throws DataAccessException {
    StringBuilder sql = new StringBuilder();
    sql.append(DELETE).append(SPACE).append(FROM).append(SPACE).append(t.getClass().getSimpleName().toLowerCase()).append(SPACE);
    sql.append(WHERE).append(SPACE).append(IDENTICAL).append(SPACE);
    PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(t.getClass());
    BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(t);
    for (int i = 0; i < pds.length; i++) {
        PropertyDescriptor pd = pds[i];
        String name = pd.getName();
        if (!CLASS.equals(name) && beanWrapper.isReadableProperty(name) && beanWrapper.getPropertyValue(name) != null) {
            sql.append(AND).append(SPACE).append(CamelCaseUtils.underscoreName(name)).append(SPACE);
            sql.append(EQUAL).append(SPACE).append(COLON).append(name).append(SPACE);
        }
    }
    return namedJdbcTemplate.update(sql.toString(), new BeanPropertySqlParameterSource(t));
}
 
Example 13
Project: appframework   File: UserDaoJdbcImpl.java   Source Code and License 7 votes vote down vote up
@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();
}
 
Example 14
Project: appframework   File: UserDaoJdbcImpl.java   Source Code and License 7 votes vote down vote up
@Override
	public List<User> listUser(User query) {
		StringBuffer sql = new StringBuffer("");
		sql.append(" select * ").append("\n");
		sql.append(" from user ").append("\n");
		sql.append(" where 1=1 ").append("\n");
		
		if(null != query.getId()){
			sql.append(" and id = :id  ").append("\n");
		}
		sql.append(" order by id desc ").append("\n");
		
		SqlParameterSource paramSource = new BeanPropertySqlParameterSource(query);
		
//		RowMapper<User> rowMapper = ParameterizedBeanPropertyRowMapper.newInstance(User.class);
		
	    BeanPropertyRowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
		
		return getDao().query(sql.toString(), paramSource, rowMapper);

	}
 
Example 15
Project: DevOps-for-Web-Development   File: JdbcOwnerRepositoryImpl.java   Source Code and License 6 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
Project: DevOps-for-Web-Development   File: JdbcOwnerRepositoryImpl.java   Source Code and License 6 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
Project: tc   File: TcDbExtensionLogger.java   Source Code and License 6 votes vote down vote up
protected void doInsert(TcExtensionLog tcExtensionLog) {
    int affectedLine = namedParameterJdbcTemplate.update(EXTENSION_LOGGER_INSERT_SQL,
            new BeanPropertySqlParameterSource(tcExtensionLog));
    if (!Objects.equals(affectedLine, 1)) {
        log.error("extension logger log crashed [{}]", tcExtensionLog);
    }
}
 
Example 18
Project: nbone   File: NamedJdbcDao.java   Source Code and License 6 votes vote down vote up
@Override
public int insert(Object object) {
	SqlModel<Object> sqlModel = sqlBuilder.insertSelectiveSql(object);
	checkSqlModel(sqlModel);
	
	SqlParameterSource paramSource =  new BeanPropertySqlParameterSource(object);
	return namedPjdbcTemplate.update(sqlModel.getSql(), paramSource);
}
 
Example 19
Project: nbone   File: NamedJdbcDao.java   Source Code and License 6 votes vote down vote up
@Override
public Serializable save(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);
	return generatedKeyHolder.getKey();
}
 
Example 20
Project: nbone   File: NamedJdbcDao.java   Source Code and License 6 votes vote down vote up
@Override
public int updateSelective(Object object) {
	SqlModel<Object> sqlModel = sqlBuilder.updateSelectiveSql(object);
	checkSqlModel(sqlModel);
	
	SqlParameterSource paramSource =  new BeanPropertySqlParameterSource(object);
	
	return namedPjdbcTemplate.update(sqlModel.getSql(), paramSource);
}
 
Example 21
Project: nbone   File: NamedJdbcDao.java   Source Code and License 6 votes vote down vote up
@Override
public int delete(Object object) {
	SqlModel<Object> sqlModel = sqlBuilder.deleteSqlByEntityParams(object, true);
	checkSqlModel(sqlModel);
	
	SqlParameterSource paramSource =  new BeanPropertySqlParameterSource(object);
	
	return namedPjdbcTemplate.update(sqlModel.getSql(), paramSource);
}
 
Example 22
Project: nbone   File: NamedJdbcDao.java   Source Code and License 6 votes vote down vote up
@Override
public int deleteByEntityParams(Object object) {
	SqlModel<Object> sqlModel = sqlBuilder.deleteSqlByEntityParams(object, false);
	checkSqlModel(sqlModel);
	
	SqlParameterSource paramSource =  new BeanPropertySqlParameterSource(object);
	
	return namedPjdbcTemplate.update(sqlModel.getSql(), paramSource);
}
 
Example 23
Project: nbone   File: NamedJdbcDao.java   Source Code and License 6 votes vote down vote up
public <T> T get(Object object){
	SqlModel<Object> sqlModel = sqlBuilder.selectSqlById(object);
	checkSqlModel(sqlModel);
		
	RowMapper<T> rowMapper =   (RowMapper<T>) sqlModel.getRowMapper();
	List<T> list = namedPjdbcTemplate.query(sqlModel.getSql(),new BeanPropertySqlParameterSource(object),rowMapper);
	int row ;
	if(list != null && (row = list.size()) > 0){
		if(row > 1){
			logger.warn("Primary Key query result return multiple lines ["+row+"].thinking");
		}
		return list.get(0);
	}
	return null;
}
 
Example 24
Project: nbone   File: NamedJdbcDao.java   Source Code and License 6 votes vote down vote up
@Override
public long count(Object object) {
	SqlModel<Object> sqlModel = sqlBuilder.countSql(object);
	checkSqlModel(sqlModel);
	SqlParameterSource parameterSource =  new BeanPropertySqlParameterSource(object);
	
	Number number = namedPjdbcTemplate.queryForObject(sqlModel.getSql(),parameterSource, Long.class);
	return (number != null ? number.longValue() : 0);
}
 
Example 25
Project: nbone   File: NamedJdbcDao.java   Source Code and License 6 votes vote down vote up
@Override
public <T> List<T> getForList(Object object, FieldLevel fieldLevel,String afterWhere) {
	
	SqlModel<Object> sqlModel = sqlBuilder.selectSql(object,fieldLevel,afterWhere);
	checkSqlModel(sqlModel);
		
	RowMapper<T> rowMapper =   (RowMapper<T>) sqlModel.getRowMapper();
	List<T> list = namedPjdbcTemplate.query(sqlModel.getSql(),new BeanPropertySqlParameterSource(object),rowMapper);
	return list;
}
 
Example 26
Project: nbone   File: NamedJdbcDao.java   Source Code and License 6 votes vote down vote up
@Override
public <T> List<T> queryForList(Object object, FieldLevel fieldLevel,String afterWhere) {
	SqlModel<Object> sqlModel = sqlBuilder.simpleSelectSql(object,fieldLevel,afterWhere);
	checkSqlModel(sqlModel);
		
	RowMapper<T> rowMapper =   (RowMapper<T>) sqlModel.getRowMapper();
	List<T> list = namedPjdbcTemplate.query(sqlModel.getSql(),new BeanPropertySqlParameterSource(object),rowMapper);
	return list;
}
 
Example 27
Project: nbone   File: NamedJdbcDao.java   Source Code and License 6 votes vote down vote up
@Override
public int[] batchUpdate(Object[] objects) {
	//XXX: thinking 共享第一实体的sql
	SqlModel<Object> sqlModel = sqlBuilder.updateSql(objects[0]);
	checkSqlModel(sqlModel);
		
	SqlParameterSource[] batchArgs = new BeanPropertySqlParameterSource[objects.length];
	for (int i = 0; i < objects.length; i++) {
		batchArgs[i] = new BeanPropertySqlParameterSource(objects[i]);
	}
	int[] rows = namedPjdbcTemplate.batchUpdate(sqlModel.getSql(), batchArgs);
	return rows;
	
}
 
Example 28
Project: nbone   File: NamedJdbcDao.java   Source Code and License 6 votes vote down vote up
@Override
public <T> List<T> getForListWithFieldNames(Object object, String[] fieldNames,boolean dbFieldMode) {
	SqlConfig sqlConfig = new SqlConfig(-1);
	sqlConfig.setFieldNames(fieldNames);
	sqlConfig.setDbFieldMode(dbFieldMode);
	
	SqlModel<Object> sqlModel= sqlBuilder.selectSql(object, sqlConfig);
	checkSqlModel(sqlModel);
	
	RowMapper<T> rowMapper =   (RowMapper<T>) sqlModel.getRowMapper();
	List<T> list = namedPjdbcTemplate.query(sqlModel.getSql(),new BeanPropertySqlParameterSource(object),rowMapper);
	return list;
}
 
Example 29
Project: nbone   File: NamedJdbcDao.java   Source Code and License 6 votes vote down vote up
/**
    * MathOperation is null MathOperation set +
    */
@Override
public  int updateMathOperation(Object object, MathOperation mathOperation) {
	if(mathOperation == null ){
		mathOperation = MathOperation.ADD;
	}
	SqlModel<Object> sqlModel = sqlBuilder.updateMathOperationSql(object, mathOperation);
	checkSqlModel(sqlModel);
	
	SqlParameterSource paramSource =  new BeanPropertySqlParameterSource(object);
	
	return namedPjdbcTemplate.update(sqlModel.getSql(), paramSource);
}
 
Example 30
Project: nbone   File: NamedJdbcTemplate.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> Page<T>  processPage(SqlModel<Object> sqlModel,Object object,int pageNum ,int pageSize,String... afterWhere){
	if(sqlModel == null){
		throw new BuilderSQLException("sqlModel is null.");
	}
	if(pageNum <= 0 ){
		pageNum = 1;
	}
	if(pageSize <= 0 ){
		pageSize = 10;
	}
	
	String countSql = sqlModel.getCountSql();
	String pageSql  = sqlModel.getPageSql(pageNum, pageSize);
	
	RowMapper<T> rowMapper =   (RowMapper<T>) sqlModel.getRowMapper();
	SqlParameterSource paramSource = new BeanPropertySqlParameterSource(object);
	
	List<T> rows = jdbcTemplate.query(getPreparedStatementCreator(pageSql,paramSource), rowMapper);
	
	long  count  =  this.queryForLong(countSql, paramSource);
	
	Page<T> page  = new PageImpl<T>(rows, null,count);
	
	return page;
	
}
 
Example 31
Project: cacheonix-core   File: SimpleJdbcClinic.java   Source Code and License 6 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 32
Project: nics-common   File: FeatureDAOImpl.java   Source Code and License 6 votes vote down vote up
public void addCollabroomFeature(CollabroomFeature collabroomFeature) throws Exception{
	try{
 	List<String> fields = Arrays.asList(
     		SADisplayConstants.COLLAB_ROOM_ID, SADisplayConstants.FEATURE_ID);
	
 	QueryModel model = QueryManager.createQuery(SADisplayConstants.FEATURE_COLLABROOM).insertInto(fields);
 	
 	this.template.update(model.toString(), new BeanPropertySqlParameterSource(collabroomFeature));
	}catch(Exception e) {
		throw new Exception("Unhandled exception while persisting Collabroom Feature entity: " + e.getMessage());
	}
}
 
Example 33
Project: nics-common   File: FeatureDAOImpl.java   Source Code and License 6 votes vote down vote up
public void addUserFeature(UserFeature userFeature) throws Exception{
	try{
 	List<String> fields = Arrays.asList(
     		SADisplayConstants.USER_ID, SADisplayConstants.FEATURE_ID);
	
 	QueryModel model = QueryManager.createQuery(SADisplayConstants.FEATURE_USER).insertInto(fields);
 	
 	this.template.update(model.toString(), new BeanPropertySqlParameterSource(userFeature));
	}catch(Exception e) {
		throw new Exception("Unhandled exception while persisting User Feature entity: " + e.getMessage());
	}
}
 
Example 34
Project: docker-workflow-plugin   File: JdbcOwnerRepositoryImpl.java   Source Code and License 6 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 35
Project: summerb   File: PasswordDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
public int updateUserPassword(String userUuid, String newPasswordHash) {
	Password pwd = new Password();
	pwd.setUserUuid(userUuid);
	pwd.setPasswordHash(newPasswordHash);
	pwd.setRestorationToken(null);

	BeanPropertySqlParameterSource params = new BeanPropertySqlParameterSource(pwd);

	return jdbc.update(sqlPutPassword, params);
}
 
Example 36
Project: audit4j-demo   File: JdbcOwnerRepositoryImpl.java   Source Code and License 6 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 37
Project: gomall.la   File: BaseJdbcDaoImpl.java   Source Code and License 6 votes vote down vote up
public <T> int updateNamed(String namedSql, T bean) {
	String sql = NamedParameterUtils.parseSqlStatementIntoString(namedSql);
	ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(namedSql);
	BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(bean);
	List<SqlParameter> params = NamedParameterUtils.buildSqlParameterList(parsedSql, source);
	Object[] args = NamedParameterUtils.buildValueArray(parsedSql, source, params);
	return jdbcTemplate.update(sql, args);

}
 
Example 38
Project: gomall.la   File: BaseJdbcDaoImpl.java   Source Code and License 6 votes vote down vote up
public <T> int[] updateNamed(String namedSql, List<T> beans) {
	String sql = NamedParameterUtils.parseSqlStatementIntoString(namedSql);
	ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(namedSql);
	List<Object[]> batchArgs = new ArrayList<Object[]>();
	for (T bean : beans) {
		BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(bean);
		List<SqlParameter> params = NamedParameterUtils.buildSqlParameterList(parsedSql, source);
		Object[] args = NamedParameterUtils.buildValueArray(parsedSql, source, params);
		batchArgs.add(args);
	}
	return jdbcTemplate.batchUpdate(sql, batchArgs);
}
 
Example 39
Project: DependencyInjectionAgent   File: JdbcOwnerRepositoryImpl.java   Source Code and License 6 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 40
Project: spring-petclinic-study   File: JdbcOwnerRepositoryImpl.java   Source Code and License 6 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 41
Project: javase-study   File: QueryExampleHelper.java   Source Code and License 5 votes vote down vote up
public static QueryExample createUpdateExample(RelationalPathBase<?> pathBase, Object domain, Set<String> pks) {
    QueryExample example = QueryExample.newInstance();
    SqlParameterSource source = new BeanPropertySqlParameterSource(domain);
    List<Path<?>> columns = pathBase.getColumns();
    for (Path<?> path : columns) {
        String name = path.getMetadata().getName();
        String humpName = humpName(name);
        if (pks.contains(name)) {
            Validate.notNull(source.getValue(humpName), "the value of "
                    + name + "cannot be null");
            example.equalsTo(humpName, source.getValue(humpName));
        }
    }
    return example;
}
 
Example 42
Project: maven-framework-project   File: JdbcCustomerDAO.java   Source Code and 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 43
Project: maven-framework-project   File: JdbcCustomerDAO.java   Source Code and 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 44
Project: maven-framework-project   File: PGAlertDao.java   Source Code and 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 45
Project: maven-framework-project   File: PGDocumentDao.java   Source Code and 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 46
Project: oblatum   File: MappingJdbcTemplate.java   Source Code and License 5 votes vote down vote up
public <T> int update(T where, T t) throws DataAccessException {
    StringBuilder top = new StringBuilder();
    top.append(UPDATE).append(SPACE).append(where.getClass().getSimpleName().toLowerCase()).append(SPACE);
    top.append(SET).append(SPACE);
    PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(t.getClass());
    BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(t);
    int count = 0;
    for (int i = 0; i < pds.length; i++) {
        PropertyDescriptor pd = pds[i];
        String name = pd.getName();
        if (!CLASS.equals(name) && beanWrapper.isReadableProperty(name) && beanWrapper.getPropertyValue(name) != null) {
            top.append(CamelCaseUtils.underscoreName(name)).append(SPACE);
            top.append(EQUAL).append(SPACE).append(COLON).append(name).append(SPACE);
            top.append(COMMA).append(SPACE);
            count++;
        }
    }
    StringBuffer sql = new StringBuffer();
    if (count <= 0) {
        logger.error("no values for update");
        return 0;
    } else {
        sql.append(top.toString().substring(0, top.lastIndexOf(COMMA)));
    }
    sql.append(WHERE).append(SPACE).append(IDENTICAL).append(SPACE);
    parameterJoin(where, sql);
    return namedJdbcTemplate.update(sql.toString(), new BeanPropertySqlParameterSource(t));
}
 
Example 47
Project: oblatum   File: MappingJdbcTemplate.java   Source Code and License 5 votes vote down vote up
public <T> int insert(T t) throws DataAccessException {
    StringBuilder columns = new StringBuilder();
    StringBuilder values = new StringBuilder();
    columns.append(INSERT).append(SPACE).append(t.getClass().getSimpleName().toLowerCase()).append(SPACE).append(LEFT_BRACKET);
    values.append(VALUES).append(LEFT_BRACKET);
    PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(t.getClass());
    BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(t);
    int count = 0;
    for (int i = 0; i < pds.length; i++) {
        PropertyDescriptor pd = pds[i];
        String name = pd.getName();
        if (!CLASS.equals(name) && beanWrapper.isReadableProperty(name) && beanWrapper.getPropertyValue(name) != null) {
            columns.append(CamelCaseUtils.underscoreName(name)).append(COMMA).append(SPACE);
            values.append(COLON).append(name).append(COMMA).append(SPACE);
            count++;
        }
    }
    StringBuilder sql = new StringBuilder();
    if (count <= 0) {
        logger.error("no values for insert");
        return 0;
    } else {
        sql.append(columns.toString().substring(0, columns.lastIndexOf(COMMA))).append(RIGHT_BRACKET);
        sql.append(values.toString().substring(0, values.lastIndexOf(COMMA))).append(RIGHT_BRACKET);
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.namedJdbcTemplate.update(sql.toString(), new BeanPropertySqlParameterSource(t), keyHolder);
    return keyHolder.getKey().intValue();
}
 
Example 48
Project: SpringByExample   File: JdbcVehicleDaoNamedParams.java   Source Code and License 5 votes vote down vote up
@Override
//    public void insert(Vehicle vehicle) {
//        String sql = "INSERT INTO VEHICLE (VEHICLE_NO, COLOR, WHEEL, SEAT) "
//                + "VALUES (:vehicleNo, :color, :wheel, :seat)";
//        Map<String, Object> parameters = new HashMap<>();
//        parameters.put("vehicleNo", vehicle.getVehicleNo());
//        parameters.put("color", vehicle.getColor());
//        parameters.put("wheel", vehicle.getWheel());
//        parameters.put("seat", vehicle.getSeat());
//        getSimpleJdbcTemplate().update(sql, parameters);
//    }

//    public void insert(Vehicle vehicle) {
//        String sql = "INSERT INTO VEHICLE (VEHICLE_NO, COLOR, WHEEL, SEAT) "
//                + "VALUES (:vehicleNo, :color, :wheel, :seat)";
//        Map<String, Object> parameters = new HashMap<String, Object>();
//        SqlParameterSource parameterSource =
//                new MapSqlParameterSource(parameters);
//        getSimpleJdbcTemplate().update(sql, parameterSource);
//    }


//    Here is where the SqlParameterSource intermediary starts to benefit us! SqlParameterSource is
//    BeanPropertySqlParameterSource, which wraps a normal Java object as a SQL parameter source. For
//    each of the named parameters, the property with the same name will be used as the parameter value.

    public void insert(Vehicle vehicle) {
        String sql = "INSERT INTO VEHICLE (VEHICLE_NO, COLOR, WHEEL, SEAT) "
                + "VALUES (:vehicleNo, :color, :wheel, :seat)";
        SqlParameterSource parameterSource =
                new BeanPropertySqlParameterSource(vehicle);
        getSimpleJdbcTemplate().update(sql, parameterSource);
    }
 
Example 49
Project: SpringByExample   File: JdbcVehicleDaoNamedParams.java   Source Code and License 5 votes vote down vote up
@Override
public void insertBatch(List<Vehicle> vehicles) {
    String sql = "INSERT INTO VEHICLE (VEHICLE_NO, COLOR, WHEEL, SEAT) "
            + "VALUES (:vehicleNo, :color, :wheel, :seat)";
    List<SqlParameterSource> parameters = new ArrayList<SqlParameterSource>();
    for (Vehicle vehicle : vehicles) {
        parameters.add(new BeanPropertySqlParameterSource(vehicle));
    }
    getSimpleJdbcTemplate().batchUpdate(sql,
            parameters.toArray(new SqlParameterSource[0]));
}
 
Example 50
Project: appframework   File: UserDaoJdbcImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Long updateUser(User u) {
	StringBuffer sql = new StringBuffer("");
	sql.append(" update user set ");
	sql.append(" username = :username");
	sql.append(" , password = :password ");
	sql.append(" where id = :id  ");
	
	SqlParameterSource paramSource = new BeanPropertySqlParameterSource(u);
	int rows = getDao().update(sql.toString(), paramSource);
	
	return rows > 0 ? u.getId() : null;
}
 
Example 51
Project: appframework   File: UserDaoJdbcImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Long deleteUser(User u) {
	StringBuffer sql = new StringBuffer("");
	sql.append(" delete from user ");
	sql.append(" where id = :id  ");
	
	SqlParameterSource paramSource = new BeanPropertySqlParameterSource(u);
	int rows = getDao().update(sql.toString(), paramSource);
	
	return rows > 0 ? u.getId() : null;
}
 
Example 52
Project: sjdbcx   File: DefaultParamMapper.java   Source Code and License 5 votes vote down vote up
private void addBean( final MapSqlParameterSource source, final Object beanObj ){
    final BeanPropertySqlParameterSource beanSource = new BeanPropertySqlParameterSource(beanObj);

    for( final String name: beanSource.getReadablePropertyNames() ){
        source.addValue( name, beanSource.getValue( name ) );
    }
}
 
Example 53
Project: java-samples   File: JdbcInsertUsageWithSequence.java   Source Code and License 4 votes vote down vote up
/**
 * M�me chose que l'insert pr�c�dent, mais avec un twist : on set l'ID dans le user en param�tre
 */
public void saveUser(final User user){
    Number id = insert.executeAndReturnKey(new BeanPropertySqlParameterSource(user));
    user.setId(id.intValue());
}
 
Example 54
Project: java-samples   File: NamedParameter.java   Source Code and License 4 votes vote down vote up
/**
 * Si on donne le nom des champs dans le bean en tant que param�tres de la requ�te, on peut directement les mapper
 * avec un {@link BeanPropertySqlParameterSource}
 */
public int updateUserWithoutMapping(final User user) {
    String sqlUpdate = "update users set name = :name, email = :mail where id = :id";
    return namedParameterJdbcTemplate.update(sqlUpdate, new BeanPropertySqlParameterSource(user));
}
 
Example 55
Project: java-jobposter   File: JobDAO.java   Source Code and License 4 votes vote down vote up
public boolean update(Job job) {
	BeanPropertySqlParameterSource params = new BeanPropertySqlParameterSource(job);
	
	return jdbc.update("update Jobs set name=:name, text=:text, email=:email where id=:id", params) == 1;
}
 
Example 56
Project: summerb   File: AuthTokenDaoImpl.java   Source Code and License 4 votes vote down vote up
@Override
public void createAuthToken(AuthToken authToken) {
	BeanPropertySqlParameterSource params = new BeanPropertySqlParameterSource(authToken);
	jdbcInsert.execute(params);
}
 
Example 57
Project: summerb   File: UserDaoImpl.java   Source Code and License 4 votes vote down vote up
@Override
public void createUser(User user) throws DuplicateKeyException {
	BeanPropertySqlParameterSource params = new BeanPropertySqlParameterSource(user);
	jdbcInsert.execute(params);
}
 
Example 58
Project: summerb   File: UserDaoImpl.java   Source Code and License 4 votes vote down vote up
@Override
public boolean updateUser(User user) throws DuplicateKeyException {
	BeanPropertySqlParameterSource params = new BeanPropertySqlParameterSource(user);
	return jdbc.update(sqlUpdateUser, params) == 1;
}
 
Example 59
Project: summerb   File: ParameterSourceBuilderBeanPropImpl.java   Source Code and License 4 votes vote down vote up
@Override
public SqlParameterSource buildParameterSource(TDto dto) {
	return new BeanPropertySqlParameterSource(dto);
}
 
Example 60
Project: oblatum   File: MappingJdbcTemplate.java   Source Code and License 4 votes vote down vote up
public <T> T queryForObject(T t, Class<T> type) throws DataAccessException {
    return namedJdbcTemplate.queryForObject(queryJoin(t), new BeanPropertySqlParameterSource(t), new BeanPropertyRowMapper<T>(type));
}