个人觉得JdbcTemplate相较于MyBaits,Hibernate等数据库框架更容易上手,对SQL的操作也更为直观方便,所以在项目中也是一个不错的选择。在Spring Boot开启JdbcTemplate很简单,只需要引入spring-boot-starter-jdbc依赖即可。JdbcTemplate封装了许多SQL操作,具体可查阅官方文档https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html

引入依赖

spring-boot-starter-jdbc:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-jdbc</artifactId>
  4. </dependency>

数据库驱动为ojdbc6,数据源采用Druid。具体可参考https://mrbird.cc/Spring-Boot%E4%B8%AD%E4%BD%BF%E7%94%A8Mybatis.html

代码编写

数据准备:

  1. CREATE TABLE "SCOTT"."STUDENT" (
  2. "SNO" VARCHAR2(3 BYTE) NOT NULL ,
  3. "SNAME" VARCHAR2(9 BYTE) NOT NULL ,
  4. "SSEX" CHAR(2 BYTE) NOT NULL
  5. );
  6. INSERT INTO "SCOTT"."STUDENT" VALUES ('001', 'KangKang', 'M ');
  7. INSERT INTO "SCOTT"."STUDENT" VALUES ('002', 'Mike', 'M ');
  8. INSERT INTO "SCOTT"."STUDENT" VALUES ('003', 'Jane', 'F ');

这里主要演示在Dao的实现类里使用JdbcTemplate,所以其它模块代码的编写就不展示了,具体可参考文末的源码。

StudentDaoImp类代码:

  1. @Repository("studentDao")
  2. public class StudentDaoImp implements StudentDao {
  3. @Autowired
  4. private JdbcTemplate jdbcTemplate;
  5. @Override
  6. public int add(Student student) {
  7. // String sql = "insert into student(sno,sname,ssex) values(?,?,?)";
  8. // Object[] args = { student.getSno(), student.getName(), student.getSex() };
  9. // int[] argTypes = { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR };
  10. // return this.jdbcTemplate.update(sql, args, argTypes);
  11. String sql = "insert into student(sno,sname,ssex) values(:sno,:name,:sex)";
  12. NamedParameterJdbcTemplate npjt = new NamedParameterJdbcTemplate(this.jdbcTemplate.getDataSource());
  13. return npjt.update(sql, new BeanPropertySqlParameterSource(student));
  14. }
  15. @Override
  16. public int update(Student student) {
  17. String sql = "update student set sname = ?,ssex = ? where sno = ?";
  18. Object[] args = { student.getName(), student.getSex(), student.getSno() };
  19. int[] argTypes = { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR };
  20. return this.jdbcTemplate.update(sql, args, argTypes);
  21. }
  22. @Override
  23. public int deleteBysno(String sno) {
  24. String sql = "delete from student where sno = ?";
  25. Object[] args = { sno };
  26. int[] argTypes = { Types.VARCHAR };
  27. return this.jdbcTemplate.update(sql, args, argTypes);
  28. }
  29. @Override
  30. public List<Map<String, Object>> queryStudentsListMap() {
  31. String sql = "select * from student";
  32. return this.jdbcTemplate.queryForList(sql);
  33. }
  34. @Override
  35. public Student queryStudentBySno(String sno) {
  36. String sql = "select * from student where sno = ?";
  37. Object[] args = { sno };
  38. int[] argTypes = { Types.VARCHAR };
  39. List<Student> studentList = this.jdbcTemplate.query(sql, args, argTypes, new StudentMapper());
  40. if (studentList != null && studentList.size() > 0) {
  41. return studentList.get(0);
  42. } else {
  43. return null;
  44. }
  45. }
  46. }

在引入spring-boot-starter-jdbc驱动后,可直接在类中注入JdbcTemplate。由上面代码可发现,对于保存操作有两种不同的方法,当插入的表字段较多的情况下,推荐使用NamedParameterJdbcTemplate

对于返回结果,可以直接使用List<Map<String, Object>>来接收,这也是个人比较推荐使用的方式,毕竟比较简单方便;也可以使用库表对应的实体对象来接收,不过这时候我们就需要手动创建一个实现了org.springframework.jdbc.core.RowMapper的对象,用于将实体对象属性和库表字段一一对应:

  1. public class StudentMapper implements RowMapper<Student>{
  2. @Override
  3. public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
  4. Student student = new Student();
  5. student.setSno(rs.getString("sno"));
  6. student.setName(rs.getString("sname"));
  7. student.setSex(rs.getString("ssex"));
  8. return student;
  9. }
  10. }

RowMapper问题

可以采用Spring提供的BeanPropertyRowMapper。这个mapper中在initialize初始化中会对Java属性名转化为数据库字段名。会在遇到大写字母X后转换为_x

注意:如果数据库字段是A_XX这样,而属性名为aXx。如果使用IDEA自带的生成setter方法会生成setaXx就没有问题。如果使用lombok会生成setter字段:setAXx,就会不匹配,这个时候需要修改一下BeanPropertyRowMapper:

  1. protected void initialize(Class<T> mappedClass) {
  2. this.mappedClass = mappedClass;
  3. this.mappedFields = new HashMap<String, PropertyDescriptor>();
  4. this.mappedProperties = new HashSet<String>();
  5. PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
  6. for (PropertyDescriptor pd : pds) {
  7. if (pd.getWriteMethod() != null) {
  8. this.mappedFields.put(lowerCaseName(pd.getName()), pd);
  9. String underscoredName = underscoreName(pd.getName());
  10. if (!lowerCaseName(pd.getName()).equals(underscoredName)) {
  11. this.mappedFields.put(underscoredName, pd);
  12. }
  13. this.mappedProperties.add(pd.getName());
  14. }
  15. }
  16. }
  17. /**
  18. * Convert the given name to lower case.
  19. * By default, conversions will happen within the US locale.
  20. * @param name the original name
  21. * @return the converted name
  22. * @since 4.2
  23. */
  24. protected String lowerCaseName(String name) {
  25. return name.toLowerCase(Locale.US);
  26. }
  27. /**
  28. * Convert a name in camelCase to an underscored name in lower case.
  29. * Any upper case letters are converted to lower case with a preceding underscore.
  30. *
  31. * @param name the original name
  32. * @return the converted name
  33. * @see #lowerCaseName
  34. * @since 4.2
  35. */
  36. protected String underscoreName(String name) {
  37. if (!StringUtils.hasLength(name)) {
  38. return "";
  39. }
  40. StringBuilder result = new StringBuilder();
  41. result.append(lowerCaseName(name.substring(0, 1)));
  42. for (int i = 1; i < name.length(); i++) {
  43. String s = name.substring(i, i + 1);
  44. String slc = lowerCaseName(s);
  45. if (!s.equals(slc)) {
  46. result.append("_").append(slc);
  47. } else {
  48. result.append(s);
  49. }
  50. }
  51. return result.toString();
  52. }

对比原版的BeanPropertyRowMapper

  1. /**
  2. * Convert a name in camelCase to an underscored name in lower case.
  3. * Any upper case letters are converted to lower case with a preceding underscore.
  4. * @param name the original name
  5. * @return the converted name
  6. * @since 4.2
  7. * @see #lowerCaseName
  8. */
  9. protected String underscoreName(String name) {
  10. if (!StringUtils.hasLength(name)) {
  11. return "";
  12. }
  13. StringBuilder result = new StringBuilder();
  14. result.append(Character.toLowerCase(name.charAt(0)));
  15. for (int i = 1; i < name.length(); i++) {
  16. char c = name.charAt(i);
  17. if (Character.isUpperCase(c)) {
  18. result.append('_').append(Character.toLowerCase(c));
  19. }
  20. else {
  21. result.append(c);
  22. }
  23. }
  24. return result.toString();
  25. }

其中PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors()方法用于获取的类的属性。获取的属性不是类的成员变量。

  1. public class demo {
  2. public String name;
  3. private String fOpen;
  4. public String getName() {
  5. return name;
  6. }
  7. public void setNameTest(String name) {
  8. this.name = name;
  9. }
  10. public String getfOpen() {
  11. return fOpen;
  12. }
  13. public void setfOpen(String fOpen) {
  14. this.fOpen = fOpen;
  15. }
  16. public static void main(String[] args) {
  17. try {
  18. PropertyDescriptor[] pds = Introspector.getBeanInfo(demo.class).getPropertyDescriptors();
  19. for(PropertyDescriptor pd : pds){
  20. System.out.println(pd.getName());
  21. }
  22. } catch (IntrospectionException e) {
  23. e.printStackTrace();
  24. }
  25. }

打个断点看PropertyDescriptor
Screen Shot 2022-05-12 at 4.15.40 PM.png
Screen Shot 2022-05-12 at 4.15.58 PM.png
Screen Shot 2022-05-12 at 4.17.45 PM.png
输出的结果为:

  1. class
  2. fOpen
  3. name
  4. nameTest

测试

最终项目目录如下图所示:

Spring Boot中使用JdbcTemplate - 图4

启动项目,测试插入数据http://localhost:8080/web/addstudent?sno=004&name=Maria&sex=F

Spring Boot中使用JdbcTemplate - 图5

查询所有学生数据http://localhost:8080/web/queryallstudent:

Spring Boot中使用JdbcTemplate - 图6

测试删除http://localhost:8080/web/deletestudent?sno=004

Spring Boot中使用JdbcTemplate - 图7