스프링, 마이바티스, 웹스퀘어5(Websquare5) 연동 간단 예제 실습_최성찬

FSP 1 293 05.03 10:32

스프링, 마이바티스, 웹스퀘어5(Websquare5) 연동 간단 예제 실습

 

작성자 : 최성찬

 

c903b4daf5908ef8a243a9aa218aaeaf_1525253
 

 

쿼리

use mydb;

 

create table employee(

empno int(255) primary key auto_increment,

ename varchar(20),

job varchar(20),

salary int(255),

hiredate date

);

 

insert into employee values(default,'최성찬','개발자','3000','20170502');

insert into employee values(default,'홍길동','퍼블리셔','2500','20170402');

insert into employee values(default,'임꺾정','영업사원','2500','20170202');

insert into employee values(default,'손민정','개발자','3000','20170502');

insert into employee values(default,'이민교','개발자','3000','20170502');

insert into employee values(default,'송석원','프로젝트리더','4000','20070502');

insert into employee values(default,'김동현','개발자','3000','20170502');

insert into employee values(default,'이경민','개발자','3000','20170502');

insert into employee values(default,'박수연','개발자','3000','20170502');

 

commit;

 

 

select * from employee;


 

 

application.properties

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3307/mydb?useSSL=false

spring.datasource.username=root

 

spring.datasource.password=1234

 

EmpRestController

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpHeaders;

import org.springframework.http.HttpStatus;

import org.springframework.http.MediaType;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.CrossOrigin;

import org.springframework.web.bind.annotation.DeleteMapping;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.PutMapping;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.util.UriComponentsBuilder;

 

import com.emp.server.error.CustomErrorType;

import com.emp.server.model.Emp;

 

import com.emp.server.service.EmpService;

 

 

@CrossOrigin(origins = "*", maxAge= 3600)

@RestController

@RequestMapping("/api")

public class EmpRestController {

public static final Logger logger = LoggerFactory.getLogger(EmpRestController.class);

@Autowired

EmpService empService;

//모든 사원

 

//Get 매핑으로 할경우 웹스퀘어 에서 못받음

@PostMapping("/emp.post")

public ResponseEntity<List<Emp>> getAllEmp() {

logger.info("get All emps {}");

List<Emp> emps = empService.getAllEmps();

return new ResponseEntity<List<Emp>>(emps, HttpStatus.OK);

}

//사번으로 사원 한명 조회

@GetMapping("/emp/{empno}")

public ResponseEntity<Emp> getEmpByEmpno(@PathVariable("empno") int empno) {

logger.info("Fetching Emp with empno {}", empno);

Emp emp = empService.findByEmpno(empno);

if(!empService.isEmpExist(emp)) {

logger.error("사원이 존재 하지 않습니다", empno);

return new ResponseEntity(new CustomErrorType("해당 사번"+ empno +"을 가지고 있는 사원이 존재 하지 않습니다"),HttpStatus.NOT_FOUND);

}

return new ResponseEntity<Emp>(emp, HttpStatus.OK);

}

//사원 생성

@PostMapping("/emp/")

public ResponseEntity<?> createEmp(@RequestBody Emp emp, UriComponentsBuilder ucBuilder) {

logger.info("Creating Employee : {}", emp);

if(empService.isEmpExist(emp)) {

logger.error("사번중복, 사원이 이미 존재합니다", emp.getEname());

return new ResponseEntity(new CustomErrorType("사원을 생성할수 없습니다. 해당 사원 [사번"+emp.getEmpno()+"] [이름:"+emp.getEname()+"]이 이미 존재 합니다."),HttpStatus.CONFLICT);

}

empService.createEmp(emp);

HttpHeaders headers = new HttpHeaders();

headers.setLocation(ucBuilder.path("/api/emp/{empno}").buildAndExpand(emp.getEmpno()).toUri());

return new ResponseEntity<String>(headers,HttpStatus.CREATED);

}

//사원 정보 수정

@PutMapping("/emp/")

public ResponseEntity<?> updateEmp(@PathVariable("empno") int empno, @RequestBody Emp emp) {

logger.info("Updating Emp with empno {}", empno);

if(!empService.isEmpExist(emp)) {

logger.error("사원이 존재 하지 않습니다", empno);

return new ResponseEntity(new CustomErrorType("해당 사번"+ empno +"을 가지고 있는 사원이 존재 하지 않습니다"),HttpStatus.NOT_FOUND);

}

Emp currentEmp = emp;

currentEmp.setSalary(emp.getSalary());

currentEmp.setEname(emp.getEname());

currentEmp.setJob(emp.getJob());

empService.updateEmp(currentEmp);

return new ResponseEntity<Emp>(currentEmp, HttpStatus.OK);

}

//사원삭제

@DeleteMapping("/emp/{empno}")

public ResponseEntity<?> deleteEmp(@PathVariable("empno") int empno) {

logger.info("Fetching & Deleting Emp with empno {}", empno);

Emp emp = empService.findByEmpno(empno);

if(!empService.isEmpExist(emp)) {

logger.error("삭제할수 없습니다 사원이 이미 존재 하지 않습니다", empno);

return new ResponseEntity(new CustomErrorType("해당 사번"+ empno +"을 가지고 있는 사원이 존재 하지 않습니다"),HttpStatus.NOT_FOUND);

}

empService.deleteEmpByEmpno(empno);

return new ResponseEntity<Emp>(HttpStatus.NO_CONTENT);

}

}



 

 

 

CustomerErrorType

package com.emp.server.error;

 

public class CustomErrorType {

private String errorMessage;

public CustomErrorType(String errorMessage) {

this.errorMessage = errorMessage;

}

public String getErrorMessage() {

return errorMessage;

}

 

}


 

 

 

EmpMapper

package com.emp.server.mapper;

 

import java.util.List;

 

import org.apache.ibatis.annotations.Mapper;

import org.apache.ibatis.annotations.Select;

 

import com.emp.server.model.Emp;

 

 

@Mapper

public interface EmpMapper{

public int insert(Emp emp);

public int update(Emp emp);

public int deleteByEmpNo(int empno);

@Select("SELECT * FROM employee")

public List<Emp> findAllEmps();

@Select("SELECT * FROM employee WHERE empno = #{empno}")

public Emp selectByEmpNo(int empno);

 

public int increment(int empno);

 

}


 

 

 

Emp

package com.emp.server.model;

 

import java.sql.Date;

 

public class Emp {

private int empno;  //사번

private String ename; //이름

private String job; //직무

private int salary; //급여

private Date hiredate; //입사일

public int getEmpno() {

return empno;

}

public void setEmpno(int empno) {

this.empno = empno;

}

public String getEname() {

return ename;

}

public void setEname(String ename) {

this.ename = ename;

}

public String getJob() {

return job;

}

public void setJob(String job) {

this.job = job;

}

public int getSalary() {

return salary;

}

public void setSalary(int salary) {

this.salary = salary;

}

public Date getHiredate() {

return hiredate;

}

public void setHiredate(Date hiredate) {

this.hiredate = hiredate;

 

}


 

 

EmpService

package com.emp.server.service; 

 

import java.util.List;

 

import com.emp.server.model.Emp;

 

public interface EmpService {

Emp findByEmpno(int empno);

int createEmp(Emp emp);

int updateEmp(Emp emp);

int deleteEmpByEmpno(int empno);

List<Emp> getAllEmps();

boolean isEmpExist(Emp emp);

}


 

 

EmpServiceImpl

package com.emp.server.service;

 

import java.util.List;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

 

import com.emp.server.mapper.EmpMapper;

import com.emp.server.model.Emp;

 

@Service

public class EmpServiceImpl implements EmpService{

 

@Autowired

EmpMapper empMapper;

@Override

public Emp findByEmpno(int empno) {

Emp emp = empMapper.selectByEmpNo(empno);

return emp;

}

 

@Override

public int createEmp(Emp emp) {

return empMapper.insert(emp);

}

 

@Override

public int updateEmp(Emp emp) {

return empMapper.update(emp);

}

 

@Override

public int deleteEmpByEmpno(int empno) {

return empMapper.deleteByEmpNo(empno);

}

 

@Override

public List<Emp> getAllEmps() {

return empMapper.findAllEmps();

}

 

@Override

public boolean isEmpExist(Emp emp) {

if(empMapper.selectByEmpNo(emp.getEmpno())!=null){

return true;

}else {

return false;

}

}

 

 

}


 

Mybatis-mapper/emp-mapper

<?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.emp.server.mapper.EmpMapper">

<resultMap type="Emp" id="EmpResultMap">

<result property="empno" column="EMPNO"/>

<result property="ename" column="ENAME"/>

<result property="job" column="JOB"/>

<result property="salary" column="SALARY"/>

<result property="hiredate" column="HIREDATE"/>

</resultMap>

<insert id="insert" parameterType="Emp">

INSERT INTO employee 

VALUES(default, #{ename}, #{job}, #{salary}, #{hiredate})

</insert>

 

<update id="update" parameterType="int">

UPDATE Emp 

SET name=#{ename}, age=#{age}, salary=#{salary}

WHERE empno=#{empno} 

</update>

<delete id="deleteByEmpNo" parameterType="int">

DELETE 

FROM employee

WHERE empno=#{empno}

</delete>

<select id="selectByEmpNo" parameterType="int">

SELECT *

FROM employee

WHERE empno=#{empno}

</select>

</mapper>

 

 

 

 

 

 

 

 

WebSquare Grid 작성법

 

1c8d61b0890f492edde5ae2873f9b6cc_1525296
1c8d61b0890f492edde5ae2873f9b6cc_1525296
1c8d61b0890f492edde5ae2873f9b6cc_1525296
1c8d61b0890f492edde5ae2873f9b6cc_1525296
1c8d61b0890f492edde5ae2873f9b6cc_1525296
1c8d61b0890f492edde5ae2873f9b6cc_1525296
1c8d61b0890f492edde5ae2873f9b6cc_1525296
1c8d61b0890f492edde5ae2873f9b6cc_1525296
1c8d61b0890f492edde5ae2873f9b6cc_1525296
1c8d61b0890f492edde5ae2873f9b6cc_1525296
1c8d61b0890f492edde5ae2873f9b6cc_1525296
1c8d61b0890f492edde5ae2873f9b6cc_1525296
1c8d61b0890f492edde5ae2873f9b6cc_1525296
1c8d61b0890f492edde5ae2873f9b6cc_1525296
1c8d61b0890f492edde5ae2873f9b6cc_1525296
 

 

 

1c8d61b0890f492edde5ae2873f9b6cc_1525296

미리 보기 버튼 클릭 하면

아래와 같이 실행 결과를 볼 수 있음
 

1c8d61b0890f492edde5ae2873f9b6cc_1525296
 

 

 

Comments

성찬ITS 05.19 08:49
위 예제는 간단예제로 Grid를 편하게 그리는 방법만 설명되있습니다,
 다음과정을 꼭 따라주시기 바랍니다
http://ojc.asia/bbs/board.php?bo_table=LecSpring&wr_id=794