db.url=jdbc:mysql:///test?characterEncoding=utf8&useSSL=true&serverTimezone=GMT db.username=root db.password=root db.dirverClass=com.mysql.cj.jdbc.Driver
db-config.properties这里的Driver和版本有关系,笔者的Connection/j 是6.0.5的。
UserVO.java类
1 package com.spring.model; 2 3 public class UserVO { 4 private int id; 5 private String name; 6 private String pwd; 7 8 public int getId() { 9 return id; 10 } 11 public void setId(int id) { 12 this.id = id; 13 } 14 public String getName() { 15 return name; 16 } 17 public void setName(String name) { 18 this.name = name; 19 } 20 public String getPwd() { 21 return pwd; 22 } 23 public void setPwd(String pwd) { 24 this.pwd = pwd; 25 } 26 }
UserVO.javaUserDao.java类
1 package com.spring.db; 2 3 import java.sql.ResultSet; 4 import java.sql.SQLException; 5 import java.util.List; 6 7 import org.springframework.jdbc.core.JdbcTemplate; 8 import org.springframework.jdbc.core.RowMapper; 9 10 import com.spring.model.UserVO; 11 12 public class UserDao { 13 private JdbcTemplate jdbcTemplate; 14 15 public JdbcTemplate getJdbcTemplate() { 16 return jdbcTemplate; 17 } 18 19 public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { 20 this.jdbcTemplate = jdbcTemplate; 21 } 22 @SuppressWarnings({ "unchecked", "rawtypes" }) 23 public List<UserVO> find(){ 24 String sql="select * from userbo";//这里也可以添加查询限制条件 25 return jdbcTemplate.query(sql, new RowMapper(){ 26 27 public Object mapRow(ResultSet rs, int num) throws SQLException { 28 UserVO uservo=new UserVO(); 29 uservo.setId(rs.getInt("USERID")); 30 uservo.setName(rs.getString("USERNAME")); 31 uservo.setPwd(rs.getString("USERPSW")); 32 return uservo; 33 } 34 }); 35 } 36 }
UserDao.java