참고(MyBatis에 대하여)
참고(JPA와 MyBatis 장단점)
# MySQL DB 설정
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=Asia/Seoul
spring.datasource.username=mysql아이디
spring.datasource.password=비밀번호
package com.myapp.mybatis.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.myapp.mybatis.model.User;
@Mapper // jpa의 repository와 같음
public interface UserMapper {
@Select("select * from user where id = #{id}") // #{매개변수}, 메소드에 설정한 매개변수가 여기 들어감
User getUser(String id); // id로 DB user테이블에서 찾아 User객체 Return
@Select("select * from user")
List<User> getUserList();
@Insert("insert into user values (#{id}, #{name}, #{phone}, #{address})")
void insertUser(String id, String name, String phone, String address);
@Update("update user set name=#{name}, phone=#{phone}, address=#{address} where id=#{id}")
int updateUser(String id, String name, String phone, String address);
@Delete("delete from user where id=#{id}")
void deleteUser(String id);
}
package com.myapp.mybatis.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.myapp.mybatis.mapper.UserMapper;
import com.myapp.mybatis.model.User;
@RestController // view 없이 바로 return
@RequestMapping("/users")
public class UserController {
@Autowired
private UserMapper usermapper;
@GetMapping("/{id}")
public User getUser(@PathVariable("id") String id) {
// mybatis는 repository 대신 매퍼를 만듬
User user = usermapper.getUser(id);
return user;
}
@GetMapping
public List<User> getUserList() {
List<User> userList = usermapper.getUserList();
return userList;
}
@PostMapping
public void createUser(@RequestParam("id") String id, @RequestParam("name") String name,
@RequestParam("phone") String phone, @RequestParam("address") String address) {
usermapper.insertUser(id, name, phone, address);
}
@PutMapping("/{id}")
public void updateUser(@PathVariable("id") String id, @RequestParam("name") String name,
@RequestParam("phone") String phone, @RequestParam("address") String address) {
usermapper.updateUser(id, name, phone, address);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable("id") String id) {
usermapper.deleteUser(id);
}
}