引入pom支持,此处使用mysql数据库
<!-- MYSQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Spring Boot JDBC -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
配置文件增加数据库链接
#Mysql
spring.datasource.url=jdbc:mysql://localhost:3306/duck
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=org.gjt.mm.mysql.Driver
添加实体类SysUser
package com.duck.bean;
public class SysUser {
public Integer id;
public String realName;
public String loginName;
public String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
添加Service接口,SysUserService
package com.duck.service;
import com.duck.bean.SysUser;
import java.util.List;
import java.util.Map;
public interface SysUserService {
List<SysUser> querySysUser(Map map);
}
添加实现类SysUserServiceImpl,并引入JdbcTemplate模板,实现SysUserService接口
package com.duck.service;
import com.duck.bean.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
@Service
public class SysUserServiceImpl implements SysUserService{
@Autowired
JdbcTemplate jdbcTemplate;
public List<SysUser> querySysUser(Map map){
String sql = "select * from sys_user ";
return jdbcTemplate.query(sql, new RowMapper<SysUser>() {
@Override
public SysUser mapRow(ResultSet resultSet, int i) throws SQLException {
SysUser sysUser = new SysUser();
sysUser.setId(resultSet.getInt("id"));
sysUser.setLoginName(resultSet.getString("login_name"));
sysUser.setRealName(resultSet.getString("real_name"));
sysUser.setPassword(resultSet.getString("password"));
return sysUser;
}
});
}
}
Controller增加访问入口方法,并访问
@RequestMapping("querySysUser")
public @ResponseBody List<SysUser> querySysUser(){
logger.info("查询用户");
List<SysUser> sysUserList = sysUserService.querySysUser(new HashMap());
return sysUserList;
}
项目结构如下