the first attempt to use springboot, intended to use jdbctemplate, but the startup project reported an error.
Database is mysql5.7, operating system ubuntu16.04
pom.xml
<name>demoboot</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
application.proerties
spring.datasource.url=jdbc:mysql://localhost:3306/demo01
spring.datasource.username=
spring.datasource.password=
DemobootApplication.java
@SpringBootApplication
public class DemobootApplication
{
public static void main(String[] args)
{
SpringApplication.run(DemobootApplication.class, args);
}
}
MainController.java
@Controller
public class MainController
{
@Autowired
private UserDao userDao;
@ResponseBody
@RequestMapping(value = "/usr/{id}", method = RequestMethod.GET)
public String doGet(@PathVariable Long id)
{
User user = userDao.getUserById(id);
ObjectMapper mapper = new ObjectMapper();
String respJson;
try
{
respJson = mapper.writeValueAsString(user);
}
catch (JsonProcessingException e)
{
e.printStackTrace();
respJson = "";
}
return respJson;
}
}
UserDao.java
@Repository
public class UserDao
{
@Autowired
private JdbcTemplate jdbcTemplate;
public User getUserById(Long userId)
{
String sql = "select * from t_user where user_id=?";
try
{
Map<String, Object> resultMap = jdbcTemplate.queryForMap(sql, userId);
User user = new User();
user.setUserId((Long) resultMap.get("user_id"));
user.setUsername((String) resultMap.get("username"));
user.setPassword((String) resultMap.get("password"));
return user;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}