mysql使用JdbcTemplate

 使用JdbcTemplate练习 常用的 query:

query()  queryForMap()  queryForObject()  queryForList()

import mysqltesting.ljs.BaseMysqlTest;
import mysqltesting.ljs.Entity.Student;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import java.sql.ResultSet;
import java.util.List;
import java.util.Map;

public class AControllerTest extends BaseMysqlTest {
    @Autowired
    private AController controller;

    @Test
    public void test() {
        controller.updateAddress();
    }

    /**
     * query(String sql,new RowMapper(){重写  mapRow(ResultSet rs,int i)})
     * 返回 List
     *
     *  queryForMap 直接 queryForMap(String sql,Object... objs)
     *
     *  queryForObject - > 和query的方式一样 但是只返回一条记录
     *
     *  queryForList(String sql)返回List> 类似于返回多条的queryForMap
     *
     *  BeanPropertyRowMapper(class mappedClass) 会自动封装所有同名的属性 相比前面实现匿名内部类 new RowMapper要好的多
     */
    @Test
    public void test2() {
        String sql = "select * from student where servlet > 40";

        List query = template.query(sql, (ResultSet rs, int i) -> {
            Student stu = new Student();
            stu.setId(rs.getString("id"));
            stu.setUsername(rs.getString("username"));
            stu.setServlet(rs.getString("servlet"));
            stu.setJsp(rs.getString("jsp"));
            stu.setAddress(rs.getString("address"));
            return stu;
        });

        System.out.println(query.toString());
    }

    @Test
    public void test3(){
        String sql = "select * from student where servlet > 40";

        List query = template.query(sql, new BeanPropertyRowMapper<>(Student.class));

        System.out.println(query.toString());
    }

    @Test
    public void test4(){
        String sql = "select * from student where servlet > 40";

        List> query = template.queryForList(sql);

        System.out.println(query.toString());
    }

    @Test
    public void test5(){
        String sql =  "select count(*) from student";

        Integer integer = template.queryForObject(sql, Integer.class);
//        List list = template.queryForList(sql, Integer.class);

    }
}

 

你可能感兴趣的:(mysql使用JdbcTemplate)