个人觉得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:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
数据库驱动为ojdbc6,数据源采用Druid。具体可参考https://mrbird.cc/Spring-Boot%E4%B8%AD%E4%BD%BF%E7%94%A8Mybatis.html。
代码编写
数据准备:
CREATE TABLE "SCOTT"."STUDENT" (
"SNO" VARCHAR2(3 BYTE) NOT NULL ,
"SNAME" VARCHAR2(9 BYTE) NOT NULL ,
"SSEX" CHAR(2 BYTE) NOT NULL
);
INSERT INTO "SCOTT"."STUDENT" VALUES ('001', 'KangKang', 'M ');
INSERT INTO "SCOTT"."STUDENT" VALUES ('002', 'Mike', 'M ');
INSERT INTO "SCOTT"."STUDENT" VALUES ('003', 'Jane', 'F ');
这里主要演示在Dao的实现类里使用JdbcTemplate,所以其它模块代码的编写就不展示了,具体可参考文末的源码。
StudentDaoImp类代码:
@Repository("studentDao")
public class StudentDaoImp implements StudentDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public int add(Student student) {
// String sql = "insert into student(sno,sname,ssex) values(?,?,?)";
// Object[] args = { student.getSno(), student.getName(), student.getSex() };
// int[] argTypes = { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR };
// return this.jdbcTemplate.update(sql, args, argTypes);
String sql = "insert into student(sno,sname,ssex) values(:sno,:name,:sex)";
NamedParameterJdbcTemplate npjt = new NamedParameterJdbcTemplate(this.jdbcTemplate.getDataSource());
return npjt.update(sql, new BeanPropertySqlParameterSource(student));
}
@Override
public int update(Student student) {
String sql = "update student set sname = ?,ssex = ? where sno = ?";
Object[] args = { student.getName(), student.getSex(), student.getSno() };
int[] argTypes = { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR };
return this.jdbcTemplate.update(sql, args, argTypes);
}
@Override
public int deleteBysno(String sno) {
String sql = "delete from student where sno = ?";
Object[] args = { sno };
int[] argTypes = { Types.VARCHAR };
return this.jdbcTemplate.update(sql, args, argTypes);
}
@Override
public List<Map<String, Object>> queryStudentsListMap() {
String sql = "select * from student";
return this.jdbcTemplate.queryForList(sql);
}
@Override
public Student queryStudentBySno(String sno) {
String sql = "select * from student where sno = ?";
Object[] args = { sno };
int[] argTypes = { Types.VARCHAR };
List<Student> studentList = this.jdbcTemplate.query(sql, args, argTypes, new StudentMapper());
if (studentList != null && studentList.size() > 0) {
return studentList.get(0);
} else {
return null;
}
}
}
在引入spring-boot-starter-jdbc
驱动后,可直接在类中注入JdbcTemplate。由上面代码可发现,对于保存操作有两种不同的方法,当插入的表字段较多的情况下,推荐使用NamedParameterJdbcTemplate
。
对于返回结果,可以直接使用List<Map<String, Object>>
来接收,这也是个人比较推荐使用的方式,毕竟比较简单方便;也可以使用库表对应的实体对象来接收,不过这时候我们就需要手动创建一个实现了org.springframework.jdbc.core.RowMapper
的对象,用于将实体对象属性和库表字段一一对应:
public class StudentMapper implements RowMapper<Student>{
@Override
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student student = new Student();
student.setSno(rs.getString("sno"));
student.setName(rs.getString("sname"));
student.setSex(rs.getString("ssex"));
return student;
}
}
RowMapper问题
可以采用Spring提供的BeanPropertyRowMapper
。这个mapper中在initialize初始化中会对Java属性名转化为数据库字段名。会在遇到大写字母X
后转换为_x
。
注意:如果数据库字段是A_XX
这样,而属性名为aXx
。如果使用IDEA自带的生成setter方法会生成setaXx
就没有问题。如果使用lombok
会生成setter字段:setAXx
,就会不匹配,这个时候需要修改一下BeanPropertyRowMapper
:
protected void initialize(Class<T> mappedClass) {
this.mappedClass = mappedClass;
this.mappedFields = new HashMap<String, PropertyDescriptor>();
this.mappedProperties = new HashSet<String>();
PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
for (PropertyDescriptor pd : pds) {
if (pd.getWriteMethod() != null) {
this.mappedFields.put(lowerCaseName(pd.getName()), pd);
String underscoredName = underscoreName(pd.getName());
if (!lowerCaseName(pd.getName()).equals(underscoredName)) {
this.mappedFields.put(underscoredName, pd);
}
this.mappedProperties.add(pd.getName());
}
}
}
/**
* Convert the given name to lower case.
* By default, conversions will happen within the US locale.
* @param name the original name
* @return the converted name
* @since 4.2
*/
protected String lowerCaseName(String name) {
return name.toLowerCase(Locale.US);
}
/**
* Convert a name in camelCase to an underscored name in lower case.
* Any upper case letters are converted to lower case with a preceding underscore.
*
* @param name the original name
* @return the converted name
* @see #lowerCaseName
* @since 4.2
*/
protected String underscoreName(String name) {
if (!StringUtils.hasLength(name)) {
return "";
}
StringBuilder result = new StringBuilder();
result.append(lowerCaseName(name.substring(0, 1)));
for (int i = 1; i < name.length(); i++) {
String s = name.substring(i, i + 1);
String slc = lowerCaseName(s);
if (!s.equals(slc)) {
result.append("_").append(slc);
} else {
result.append(s);
}
}
return result.toString();
}
对比原版的BeanPropertyRowMapper
/**
* Convert a name in camelCase to an underscored name in lower case.
* Any upper case letters are converted to lower case with a preceding underscore.
* @param name the original name
* @return the converted name
* @since 4.2
* @see #lowerCaseName
*/
protected String underscoreName(String name) {
if (!StringUtils.hasLength(name)) {
return "";
}
StringBuilder result = new StringBuilder();
result.append(Character.toLowerCase(name.charAt(0)));
for (int i = 1; i < name.length(); i++) {
char c = name.charAt(i);
if (Character.isUpperCase(c)) {
result.append('_').append(Character.toLowerCase(c));
}
else {
result.append(c);
}
}
return result.toString();
}
其中PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors()
方法用于获取的类的属性。获取的属性不是类的成员变量。
public class demo {
public String name;
private String fOpen;
public String getName() {
return name;
}
public void setNameTest(String name) {
this.name = name;
}
public String getfOpen() {
return fOpen;
}
public void setfOpen(String fOpen) {
this.fOpen = fOpen;
}
public static void main(String[] args) {
try {
PropertyDescriptor[] pds = Introspector.getBeanInfo(demo.class).getPropertyDescriptors();
for(PropertyDescriptor pd : pds){
System.out.println(pd.getName());
}
} catch (IntrospectionException e) {
e.printStackTrace();
}
}
打个断点看PropertyDescriptor
输出的结果为:
class
fOpen
name
nameTest
测试
最终项目目录如下图所示:
启动项目,测试插入数据http://localhost:8080/web/addstudent?sno=004&name=Maria&sex=F: