在pom文件中加入jdbcTemplate的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
如果在JPA已经加入的话,则可以不用引入以上的配置。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
使用jdbcTemplate
新建一个dao
/**
* @Repository 标注是一个持久化操作对象
* @author Administrator
*
*/
@Repository
public class CatDao {
@Resource
private JdbcTemplate jdbcTemplate;
public Cat selectByCatName(String catName) {
/**
* 定义一个sql语句
* 定义一个RowMapper
* 执行查询方法
*/
String sql = "select * from cat where cat_name = ?";
RowMapper<Cat> rowMapper = new BeanPropertyRowMapper<Cat>(Cat.class);
Cat cat = jdbcTemplate.queryForObject(sql,new Object[] {catName}, rowMapper);
return cat;
}
}
service
package com.cheny.spring_boot_hello.demo.service;
import javax.annotation.Resource;
import javax.transaction.Transactional;
import org.springframework.stereotype.Service;
import com.cheny.spring_boot_hello.demo.bean.Cat;
import com.cheny.spring_boot_hello.demo.dao.CatDao;
import com.cheny.spring_boot_hello.demo.repository.Cat2Repository;
import com.cheny.spring_boot_hello.demo.repository.CatRepository;
@Service
public class CatService {
@Resource
private CatDao catDao;
public Cat selectByCatName(String catName) {
return catDao.selectByCatName(catName);
}
}
controller
package com.cheny.spring_boot_hello.demo.controller;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cheny.spring_boot_hello.demo.bean.Cat;
import com.cheny.spring_boot_hello.demo.service.CatService;
@RestController
@RequestMapping("/cat")
public class CatController {
@Resource
private CatService catService;
@RequestMapping("/selectByCatName")
public Cat selectByCatName(String catName){
return catService.selectByCatName(catName);
}
}