iT邦幫忙

2023 iThome 鐵人賽

DAY 27
0

Day26 - SSM

前言

寫應用程式最重要的一塊就是跟資料庫串接,本日今日將討論Web開發常見的組合之一SSM(Spring MVC、Spring、Mybatis),來創建一個簡單的存取DB的簡單範例

專案建立

創建module

https://ithelp.ithome.com.tw/upload/images/20231012/20128084mHniOKuA7s.png
https://ithelp.ithome.com.tw/upload/images/20231012/201280848vzoDvsb0D.png

idea plugin

https://ithelp.ithome.com.tw/upload/images/20231012/20128084nJtg1kugKz.png
在mapper interface name可以快速產生對應xml
https://ithelp.ithome.com.tw/upload/images/20231012/20128084Ttl4udy1fu.png
在method可以在xml產生對應sql select
https://ithelp.ithome.com.tw/upload/images/20231012/20128084HwNbFuZAsa.png

SSM

系統初始化SQL

schema.sql

CREATE TABLE employees (
   emp_no      INT    NOT NULL,
   emp_name  VARCHAR(14)  NOT NULL
);

data.sql

INSERT INTO employees (emp_no,emp_name)
VALUES
('1','james syu'),
('2','Josph Lin');

mybatis

Bean

@Data
public class Employee {
    private int empId;
    private String empName;
}

Mapper

public interface EmpMapper {
    Employee getEmpById(@Param("id") int id);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.swj.mapper.EmpMapper">
    <select id="getEmpById" resultType="com.swj.bean.Employee">
        select * from EMPLOYEES
        where emp_no = #{id}
    </select>
</mapper>  

yaml設定檔

spring:
  datasource:
    driver-class-name: 'org.h2.Driver'
    url: 'jdbc:h2:mem:springdb'
    username: 'sa'
    password:

  h2:
    console:
      enabled: true #啟動web console操作頁面
  sql:
    init: #設定系統啟動初始化SQL
      schema-locations: 'classpath:sql/schema.sql'
      data-locations: 'classpath:sql/data.sql'

mybatis:
  mapper-locations: 'classpath:/mapper/*.xml' #mapper對應的xml設定檔位置
  configuration:
    map-underscore-to-camel-case: true  #啟動sql colnun name aaa_bbb 轉成 aaaBbb

DB connect

https://ithelp.ithome.com.tw/upload/images/20231012/20128084nawuKhEn7u.png
https://ithelp.ithome.com.tw/upload/images/20231012/20128084uxJxHkokkA.png

controller

@Slf4j
@RestController
public class EmpController {
    @Autowired
    EmpMapper empMapper;

    @GetMapping("/emp/{id}")
    public Employee getEmp(@PathVariable int id){
        log.info("EmpController get:"+id);
        Employee emp = empMapper.getEmpById(id);

        return emp;
    }
}

demo result

https://ithelp.ithome.com.tw/upload/images/20231012/20128084hzFUjHHtVR.png

Reference


上一篇
Day25 - Functional Endpoints
下一篇
Day27 - Mybatis AutoConfiguration
系列文
我在 Spring Boot 3 裡面挖呀挖呀挖31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言