JdbcTemplate增删改查

package com.fang.spring.jdbcdemo1;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Repository
public class FooDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SimpleJdbcInsert simpleJdbcInsert;

    public void insertData() {
        Arrays.asList("b","c").forEach(s->{
            jdbcTemplate.update("insert into foo(bar) values(?)", s);
        });
        HashMapmap=new HashMap<>();
        map.put("bar","d");
        simpleJdbcInsert.execute(map);

    }
    public void update(){
        String sql="update Foo set bar=? where bar=?";
        //jdbcTemplate.update(sql,"bbb","b");
        jdbcTemplate.update(sql,new Object[]{"bbb","b"});
    }
    public void delete(){
        String sql="delete from  Foo where bar=?";
        jdbcTemplate.update(sql,"c");

    }
    public void listData() {
        log.info("Count: {}", jdbcTemplate.queryForObject("SELECT COUNT(*) FROM FOO", Long.class));
        //select one column 
        List list = jdbcTemplate.queryForList("select bar from foo", String.class);
        list.forEach(s->log.info("bar :{}", s));
        //select  all column :false statement
        // Listfoolist=jdbcTemplate.queryForList("select * from foo limit 1",Foo.class);
        // foolist.forEach(s->log.info("foo: {}",s));
        //select  all column :true statement
        Listfoolist=jdbcTemplate.query("select * from foo", new RowMapper(){

            @Override
            public Foo mapRow(ResultSet rs, int rowNum) throws SQLException {
                return Foo.builder().id(rs.getLong(1)).bar(rs.getString(2)).build();
            }

        });
        foolist.forEach(s->log.info("foo: {}",s));
    }
}

你可能感兴趣的:(JdbcTemplate增删改查)