SpringBoot+Mybatis 추가 삭제 실전 기록 수정
9833 단어 mybatisspringboot첨삭 하 다.
SpringBoot 와 Mybatis 는 무엇 입 니까?스스로 바 이 두 를 바 이 두 세 요.저 자 는 며칠 동안 이 프레임 워 크 에 입문 하여 임 무 를 완 성 했 고 요구 에 부합 되 는 임 무 를 완 성 했 습 니 다.그 동안 바 이 두 도 있 지만 자신 이 원 하 는 간단 하고 알 기 쉬 운 튜 토리 얼 을 찾 지 못 했 습 니 다.그래서 많은 구 덩이 를 밟 았 습 니 다.이 블 로 그 를 쓰 는 목적 은 여러분 들 이 구 덩이 를 조금 덜 밟 고 시작 하도록 하 는 것 입 니 다.
SpringBoot 프로젝트 https://start.spring.io/ 만 들 기
이 사 이 트 를 클릭 하여 Springboot 프로젝트 를 만 듭 니 다.다음 그림 은 2.1.5 입 니 다.기술 을 배 우 는 것 은 바로 새로운 것 을 배 우 는 것 입 니 다.
의존 을 선택 하고 왼쪽 아래 에 있 는 Dependencies 를 클릭 하 십시오.
마지막 으로 왼쪽 아래 에 있 는 Generate Project 를 누 르 면 프로젝트 이름 으로 시작 하 는 zip 파일 을 다운로드 하고 다운로드 가 완료 되면 작업 디 렉 터 리 에 압축 을 풀 수 있 습 니 다.
이 항목 열기
여기 서 사용 하 는 것 은 IDEA 입 니 다.다른 것 도 좋 습 니 다.예 를 들 어 eclipse 입 니 다.여 기 는 IDEA 의 조작 만 설명 하고 설치 하여 IDEA 바 이 두 를 많이 풀 었 습 니 다.설치 한 후에 IDEA 를 열 었 습 니 다.(IDEA 에 문제 가 있 는 것 을 발 견 했 습 니 다.가끔 은 자동 import 가방 이 좋 고 가끔 은 사용 하기 어 려 웠 습 니 다.구덩이!)그리고 왼쪽 상단 에 있 는 File->Open 을 선택 하 십시오.압축 을 풀 었 던 프로젝트 파일 의 pom.xml 을 찾 으 려 면 ok 을 누 르 십시오.다음 그림 입 니 다.
디 렉 터 리 구조
디 렉 터 리 구 조 를 다음 그림 으로 변경 합 니 다.
집필 을 시작 하 다
여기 서 우 리 는 인원 정보의 첨삭 과 수정 조 사 를 작성 할 것 이다.
데이터베이스 생 성 설정
my sql 데이터 베 이 스 를 열 어 test 라 는 데이터 베 이 스 를 만 든 후 person 표를 만 듭 니 다.여 기 는 Navicat 바 이 두 를 사용 하여 해독 판 을 사용 합 니 다.명령 행 으로 도 됩 니 다.다음 그림 은 홈 키 가 증가 한 다음 에 몇 개의 데 이 터 를 추가 하여 나중에 조회 할 수 있 도록 설정 하 는 것 을 기억 합 니 다.
application.yml
경로:/resources/application.yml
server:
port: 8080
spring:
datasource:
name:
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=UTC
username: root
password: root
mybatis:
mapper-locations: classpath:mapper/*.xml
Person 류경로/모델/Person.java
package com.ljsh.test.model;
public class Person {
/*
{id}
{name}
{mobile}
*/
private int id;
private String name;
private String mobile;
// Generate -> Setter and Getter -> Shift -> ok
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
// Generate -> toString() -> -> ok
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", mobile='" + mobile + '\'' +
'}';
}
}
PersonDao경로:/dao/personDao.java
package com.ljsh.test.dao;
import com.ljsh.test.model.Person;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface PersonDao {
/*
return List<Person>
*/
List<Person> getAll();
/*
ID
{id} id
*/
Person getPersonByID(int id);
/*
{id} id
*/
void delete(int id);
/*
{p} Person
*/
void update(Person p);
/*
{p} Person
*/
void newp(Person p);
}
PersonDao.xml경로:/mapper/PersonDao.xml
<?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" >
<!-- Dao -->
<mapper namespace="com.ljsh.test.dao.PersonDao" >
<!-- Person -->
<!-- -->
<sql id="table">person</sql>
<!-- id Dao xxType -->
<!-- -->
<select id="getAll" resultType="com.ljsh.test.model.Person">
SELECT
*
FROM
<include refid="table" />
</select>
<!-- id -->
<select id="getPersonById" resultType="com.ljsh.test.model.Person">
SELECT
*
FROM
<include refid="table"/>
WHERE
id = #{id}
</select>
<!-- -->
<insert id="newp" parameterType="com.ljsh.test.model.Person">
INSERT INTO
<include refid="table"/>
(name,phone)
VALUES
(#{name},#{phone})
</insert>
<!-- -->
<update id="update" parameterType="com.ljsh.test.model.Person">
UPDATE
<include refid="table"/>
SET
<!--<if test="name != null">name = #{name}</if>-->
name = #{name},phone = #{phone},status = #{status}
WHERE
id = #{id}
</update>
<!-- -->
<delete id="delete" parameterType="com.ljsh.test.model.Person">
DELETE FROM
<include refid="table"/>
WHERE
id = #{id}
</delete>
</mapper>
PersonService경로:/service/PersonService.java
package com.ljsh.test.service;
import com.ljsh.test.dao.PersonDao;
import com.ljsh.test.model.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PersonService {
@Autowired
PersonDao personDao;
/*
Service controller dao ,
dao
*/
public List<Person> getAll(){
return personDao.getAll();
}
public Person getPersonByID(int id){
return personDao.getPersonByID(id);
}
public void delete(int id){
personDao.delete(id);
}
public void update(Person p){
personDao.update(p);
}
public void newp(Person p){
personDao.newp(p);
}
}
PersonController경로:/controller/personController.java
package com.ljsh.test.controller;
import com.ljsh.test.model.Person;
import com.ljsh.test.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
public class PersonController {
@Autowired
PersonService personService;
//
@RequestMapping("/")
public ModelAndView index(){
//
ModelAndView mav = new ModelAndView("index");
List<Person> list = personService.getAll();
mav.addObject("list",list);
return mav;
}
}
전단 페이지경로:/templates/index.html
<!DOCTYPE html>
<html lang="en">
<!-- -->
<!-- thymeleaf -->
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<div id="tableP">
<table>
<caption> </caption>
<tr>
<th>Name</th>
<th>Phone</th>
</tr>
<!-- th -->
<!-- ${} -->
<tr th:each="item: ${list}">
<td th:text="${{item.name}}"> </td>
<td th:text="${{item.mobile}}"> </td>
</tr>
</table>
</div>
</div>
</body>
</html>
오른쪽 상단 실행이것 이 없 으 면 오른쪽 에서 TestApplication 오른쪽 단 추 를 눌 러 Run 을 선택 할 수 있 습 니 다.결 과 는 다음 과 같 습 니 다.
계속
불 을 끄 고 잠 이 들 었 습 니 다.좀 천천히 썼 습 니 다.지우 고 아직 쓰 지 못 했 습 니 다.댓 글 이 필요 하 다 면 계속 업데이트 하 겠 습 니 다.
총결산
이상 은 이 글 의 모든 내용 입 니 다.본 고의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 참고 학습 가 치 를 가지 기 를 바 랍 니 다.여러분 의 저희 에 대한 지지 에 감 사 드 립 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Mybatis가 키 id를 삽입하는 방법을 되돌려줍니다.mapper의 xml 파일에useGeneratedKeys 구성 KeyProperty를 사용하여 Id로 돌아가면 됩니다. PS: Mybatis의 insert에서 키 ID를 반환하는 방법 1、XyzMapper.xml 또...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.