SpringBoot使用JdbcTemplate操作增删改,SpringBoot配置postgreSQL连接

1、配置pom.xml

   引入postgresql依赖包,jdk8 对应 postgresql42.x.x

     <!-- jdbc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.8</version>
        </dependency>

2、配置properties.yml

spring:
  datasource:
    url: jdbc:postgresql://127.0.0.1:5432/ebs?useSSL=false
   characterEncoding=utf8&useSSL=false
    username: postgres
    password: root123456
    platform: postgres

3、在java中使用

在dao层使用注解加载 JdbcTemplate:

@Autowired
private JdbcTemplate jdbcTemplate;

使用JdbcTemplate操作

package com.pn.ebs.service;

import com.pn.ebs.domain.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EbsService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    public List<User> getMainDisplay(String status) {
        String sql = "select * from t_user where status=";
        logger.info("sql {}", sql);
        Object[] obj = new Object[]{status};
        return this.jdbcTemplate.query(sql, obj, new BeanPropertyRowMapper<User>(User.class));
    }

    public int insertData(User user){
        String sql = "INSERT INTO T_USER(userid, password, username, status) VALUES(?,?,?,?)";
        Object[] obj = new Object[]{user.getUserId(), user.getPassword(), user.getUserName(), user.getStatus()};
        return this.jdbcTemplate.update(sql, obj);
    }


    public int updataData(User user){
        String sql = "updata t_user set password=? where userid=?";
        Object[] obj = new Object[]{ user.getPassword(), user.getUserId()};
        return this.jdbcTemplate.update(sql, obj);
    }


}
发布了49 篇原创文章 · 获赞 19 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/shenju2011/article/details/103348512
今日推荐