JdbcTemplate

环境搭建

依赖

        
        
            cn.easyproject
            ojdbc6
            12.1.0.2.0
        

        
        
            org.springframework.boot
            spring-boot-starter-jdbc
        

yml 

server:
  port: 7100

spring:
  datasource:
    driver-class-name: oracle.jdbc.OracleDriver
    url: jdbc:oracle:thin:@127.0.0.1:1521:syh
    username: SYH
    password: syh

表结构

oracle与java数据类型映射关系

java类型 oracle类型
Timestamp 或者  Date TIMESTAMP
BigDecimal NUMBER

更新操作

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    void update() {
        // 插入
        String sql = "insert into JDBC_TEMPLATE(ID, NAME, BIRTHDAY)values(?, ?, ?)";
        Date date = new Date();   // Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        int insert = jdbcTemplate.update(sql, 10, "4", date);

        // 更新
        String sql1 = "UPDATE JDBC_TEMPLATE SET NAME = ? WHERE ID = ?";
        int update = jdbcTemplate.update(sql1, "护臂", 2);

        // 删除
        String sql2 = "DELETE FROM JDBC_TEMPLATE WHERE id = ?";
        int delete = jdbcTemplate.update(sql2, 1);
    }

查询操作

查询一条
    // 查询一条
    @Test
    void select1() {
        String sql = "select * from JDBC_TEMPLATE WHERE ID = 2";
        Map map = jdbcTemplate.queryForMap(sql);

        BigDecimal id = (BigDecimal) map.get("ID");  // oracle
        int i = id.intValue();
        String name = (String) map.get("NAME");
        Date date = (Date) map.get("BIRTHDAY");
        System.out.println(i + name + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
    }
查询多条
    // 查询多条
    @Test
    void select2() {
        String sql = "select * from JDBC_TEMPLATE";
        List> maps = jdbcTemplate.queryForList(sql);

        for (Map map : maps) {
            BigDecimal id = (BigDecimal) map.get("ID");  // oracle
            int i = id.intValue();
            String name = (String) map.get("NAME");
            Date date = (Date) map.get("BIRTHDAY");
            System.out.println(i + name + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
        }
    }
自定义类型映射器
    // 自定义类型映射器
    @Test
    void select3() {
        String sql = "select * from JDBC_TEMPLATE WHERE ID = ?";
        // sql  参数  映射
        User result = jdbcTemplate.queryForObject(sql, new Object[]{2}, new YourRowMapper());
        System.out.println(result);  // User(id=2, name=护臂, birthday=2023-12-16)
    }

    class YourRowMapper implements RowMapper {
        @Override
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User entity = new User();
            // 字段映射
            entity.setId(rs.getInt("ID"));
            entity.setName(rs.getString("NAME"));
            entity.setBirthday(rs.getDate("BIRTHDAY"));
            return entity;
        }
    }

你可能感兴趣的:(java开发模板,java)