SpringBoot----[9]---Spring Boot JdbcTemplate

在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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值