Flamme Dev
  • IntroduceMyself
  • GOAL
    • 2021년 목표
    • 회고록
      • 2020년
  • COMMON
    • 자료구조
      • 시간복잡도
      • 스택/큐
    • 코드리뷰/스터디/세미나
      • Semina
        • Version control -1 (SVN/GIT)
        • Version control - 2 (GIT)
        • PostMan
        • JMeter
      • 스터디
        • 2021년
          • EffectiveKotlin
          • 이펙티브자바
        • 2020년
          • JPA Study
            • Chap1
            • Chap3
            • Chap4
            • Chap5
            • Chap6
            • Chap7
            • Chap8
            • Chap9
            • Chap10 -1
            • Chap10-2
            • Chap10-3
            • Chap12
            • Chap 13. 웹 애플리케이션과 영속성 관리
            • Chap14
      • 코드리뷰
        • Page 1
        • 개발 생각
        • APNs 라이브러리 교체
        • 파일 삭제 분투기
        • 신입 코드리뷰
          • 2020-09-02
          • 2020-09-03
          • 2020-09-10
        • Repository
          • Repositroy(20201124)
          • Repositroy(20201123)
          • Repositroy(20201120)
          • Repositroy(20201119)
          • Repositroy(20201117)
    • 개발 서적 / 동영상 강의
      • 동영상 강의
        • 진행 중
        • 완주한 것
      • 개발 서적
        • 읽은 것
          • 손에 잡히는 10분 SQL
            • 인덱스
            • 정리 본
        • 진행 중
          • 폴리글랏 프로그래밍
          • DDD-START
            • Chapter5 리포지터리의 조회 기능
            • Chapter4 리포지터리와 모델 구현
            • Chapter3 애그리거트
            • Chapter2 아키텍쳐 개요
            • Chapter1 도메인 모델의 시작
  • INFO
    • 유스콘 준비
    • intellij
      • Command line is too long.
    • 프로그래밍의 종류
      • Async Await
      • Reactive Programming
      • Imperative Programming
      • Functional Programming
        • Naver D2 함수형 프로그래밍 강의
      • Object Oriented Programing
        • 객체지향에 대해서 알아보는 영상
      • ProcedureOriented Programming
      • RX(ReactiveX)
      • OOP VS FP
      • Declarative Programming
    • Language
      • Kotlin
        • 박재성님 강의
        • Kotlin Spring CGLIB Error
        • Kotlin의 사용
        • coroutine
        • Kotlin JVM
      • JavaScript
      • JAVA
        • DefaultNonnull
        • effective78
        • Exception
        • JsonUnWrappers
        • 명명짓기
        • @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
        • Enc Key
        • ServiceLoader
        • Annotation
        • JVM(Java Virtual Machine)
        • Java8
          • Functional 사용
          • Optional
          • Invalid Key size
        • Java13
          • Text Block
        • Basic
          • Generic
          • JVM
          • Interface, Implements
    • Framework
      • NodeJs
      • Xamarin
      • Vert.x
        • vert.x in action
        • eventbus
      • blockedthreadchecker
      • Why.. not root run..
      • Spring
        • Spring Test
        • Kotlin
        • ControllerAdvice 정리
        • JsonAnnotation
        • Spring Data R2DBC
        • SpringWebFlux
          • login
          • SpringWebFlux란?
        • JPA
          • QueryDSL 객체 주소값 확인할 것
          • SpringData-JPA에서 Save, SaveAll
          • @CompositeKey에 ManyToOne JoinColumn이 있을 경우
          • QueryDSL N+1 문제(@OneToOne)
          • QueryDSL설정
          • CreationTimestamp
          • Enum(@enumerated vs @convert)
        • SpringSecurity
          • aopAlliance
          • csrf 방어
          • antMatcher vs mvcMatcher
          • SpringSecurity를 왜 써야할까?
          • CoreSpringSecurity
            • AuthenticationProvider
            • AuthenticationManager
            • Authentication Flow
            • SecurityContextPersistenceFilter
            • SecurityContextHolder, SecurityContext
            • Authentication
            • 필터 초기화와 다중 보안 설정
            • DelegatingProxyChain, FilterChainProxy
            • 사이트 간 요청 위조 - CSRF, CsrfFilter
            • 예외 처리 및 요청 캐시 필터 : ExceptionTranslationFilter, RequestCacheAwareFilter
            • 인가 API - 권한 설정 및 표현식
            • SessionManagementFilter, ConcurrentSessionFilter
            • 동시 세션 제어 / 세션고정보호/ 세션 정책
            • AnonymousAuthenticationFilter
            • RememberMeAutheticationFilter
            • Logout,LogoutFilter
            • UsernamePasswordAuthenticationFilter
            • Form인증
            • 인증 API - 사용자 정의 보안 기능 구현
            • 인증 API - 스프링 시큐리티 의존성 추가
        • SpringMVC
          • Spring Bean Q&A
          • HttpServletRequest
          • @ControllerAdvice
          • Service와 ServiceImpl은 꼭 있어야할까?
          • SpringMVC-1
          • SpringMVC - validator와 Errors
          • SpringMVC - DispatcherServlet의 URL
          • Spring MVC - 기본설정(2) 및 HandlerInterceptor
          • SpringMVC-3
          • Spring MVC - ViewResolver
          • Spring MVC - XML/JSON
          • Spring MVC - Field Injection & Constructor Injection
        • SpringEtc
          • Transactional
          • @Atowired NullPointer
          • CircleReference
          • Mybatis
            • IBatis - sql에 Map
            • 1:1 Mapping시 Null
            • auto_Increment, selectKey
          • @Transactional
          • JacksonAnnotation
        • SpringAOP
        • SpringDI
    • Server
      • PM2
      • Tomcat
        • jks
        • Virtual Host(Port)
    • OS
      • Window
        • Active directory
      • IOS
      • Linux
        • samba/keroberos
        • Linux
          • unlimit / socket backLog
          • nohup
          • ; , & , &&, {}
          • 쉘
          • rc.local
          • ps aux | grep 프로세스이름
          • Vim
          • Su, Sudo
          • File Directory
        • IdConfig
        • 유용한 커맨드
        • 리눅스 대소문자
        • 소프트링크와 하드링크의 차이
        • ln -Tfs
        • //와 / 의 차이
        • Linux(202003)
          • rm
          • diff
          • cp
          • mv
          • tar 압축 시 어떻게 심볼릭 링크도 같이 압축할까?
          • tar 명령어
          • ln -s 심볼릭 링크
    • Network
      • API Architectural Styles
      • 포트 확인
      • HeartBeat Protocol
      • SSO(Single Sign On)
      • Cookie and Session
      • Tcp HandShake
      • WireShark
        • WireShark 옵션
        • WireShark 패킷분석
    • DataBase
      • DB락에 대해서 알아보기
      • Redis
      • MYSQL
        • Mysql TimeOut 설정
        • MysqlLog
        • SlowQuery Analyzing
        • PushNotification Stress Test
      • MSSQL
      • 데이터베이스 식별자 선택 전략
    • ETC
      • 이름 짓기
      • FFProbe
      • Talk
      • Untitled
Powered by GitBook
On this page

Was this helpful?

  1. INFO
  2. Framework
  3. Spring
  4. SpringEtc
  5. Mybatis

auto_Increment, selectKey

2020/07/16

Previous1:1 Mapping시 NullNext@Transactional

Last updated 4 years ago

Was this helpful?

Mybatis에서 auto_Increment selectKey를 사용했을 때 동일한 데이터가 들어가서 충돌이 나지 않을까?

<insert id="insertSurveyInfo" parameterType="Board">
    INSERT INTO board(boardID, title, content)
    VALUES(#{boarID}, #{title}, #{content})
    <selectKey resultType="int" keyProperty="iq" order="AFTER">
        SELECT LAST_INSERT_ID()
    </selectKey>        
</insert>

SELECT LAST_INSERT_ID()를 쓰면 되지만 이게 쓰레드 환경에서 과연 안정할까?

여기에 답변이 나와있다.

'The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.

생성된 ID는 접속별로 서버에서 유지 관리된다. 즉, 기능에 의해 주어진 클라이언트에 반환된 값이 해당 클라이언트에 의해 AUTO_INCREMENT 열에 영향을 미치는 가장 최근의 문장에 대해 생성된 첫 번째 AUTO_INCREMENT 값임을 의미한다. 이 값은 다른 클라이언트가 자체 AUTO_INGment 값을 생성하더라도 영향을 받을 수 없다. 이러한 행동은 각 클라이언트가 다른 클라이언트의 활동에 대해 염려하지 않고, 잠금이나 거래의 필요 없이 자신의 ID를 검색할 수 있도록 보장한다.

--> 즉, ID를 생성해서 유지하는 것은 컨넥션 별로 따로 관리되며, 각각의 클라이언트가 정확한 수치를 가져오기 위해 테이블에 락을 걸거나 트랜잭션을 사용 할 필요가 없다는 것이다. 고로, 그냥 연달아 쿼리 날려주면 된다.

라 다른 클라이언트는 영향을 받지 않는다고 한다. 걱정 말고 쓰도록 하자!

:

https://dev.mysql.com/doc/refman/5.5/en/information-functions.html#function_last-insert-id
Thread safety of MySQL's Select Last_Insert_IDStack Overflow
Logo