Results 1 to 3 of 3

Thread: The best practice for mysql and "upsert" with Spring ?

  1. #1
    Join Date
    Sep 2012
    Posts
    2

    Default The best practice for mysql and "upsert" with Spring ?

    I would need to update an existing row in a table in MySQL database, or create it if it is not existing.
    I am using com.mysql.jdbc.Driver.
    What is Spring way to do that, with preferably with PreparedStatement?
    I am trying to do something like this, bar1 is the key:

    Code:
    String SQL_CMND= 
    "INSERT INTO foo(bar1, bar2, bar3) values (?, ?, ?)" +
    "VALUES (1, 2, 3)" +
    "ON DUPLICATE KEY UPDATE  bar1= ?, bar2=?, bar3=?";
    
    jdbcTemplate.update(SQL_CMND, new PreparedStatementSetter() {
        public void setValues(PreparedStatement ps) throws SQLException {	
        ps.setInt(1, 1); 
        ps.setInt(2, 2);
        ps.setInt(3, 2);
    }});
    Last edited by bartpved; Sep 18th, 2012 at 01:52 AM.

  2. #2
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,632

    Default

    For starters you have 6 placeholders not 3 and you don't need a PreparedStatementSetter simply pass the objects in using the varargs update method ... Basically it should simply work (you could try and use the NamedParameterJdbcTemplate that way you can use named parameters instead of ? which can make life a little easier when duplicated parameters are needed).
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  3. #3
    Join Date
    Sep 2012
    Posts
    2

    Default

    Thanks, I think NamedParameterJdbcTemplate is exactly what I need.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •