728x90
반응형
1. 데이터베이스 설정
먼저, MariaDB에서 시퀀스를 생성합니다.
CREATE SEQUENCE seq_id
START WITH 1
INCREMENT BY 1;
2. application.yml 설정
spring:
datasource:
url: jdbc:mariadb://localhost:3306/yourdatabase
username: yourusername
password: yourpassword
driver-class-name: org.mariadb.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
properties:
hibernate.dialect: org.hibernate.dialect.MariaDBDialect
3.Entity 클래스 생성
package com.example.demo.entity
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.PrePersist
@Entity
class MyEntity(
@Id
var id: String? = null,
var name: String? = null
)
4. Service 클래스
package com.example.demo.service
import com.example.demo.entity.MyEntity
import com.example.demo.repository.MyEntityRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import javax.persistence.EntityManager
import javax.persistence.PersistenceContext
@Service
class MyEntityService(
@Autowired private val myEntityRepository: MyEntityRepository
) {
@PersistenceContext
private lateinit var entityManager: EntityManager
fun save(myEntity: MyEntity): MyEntity {
myEntity.id = generateId()
return myEntityRepository.save(myEntity)
}
private fun generateId(): String {
val datePart = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
val seqValue = getNextSequenceValue()
return datePart + String.format("%06d", seqValue)
}
private fun getNextSequenceValue(): Long {
val query = entityManager.createNativeQuery("SELECT nextval('seq_id')")
return (query.singleResult as Number).toLong()
}
fun saveMyEntity() {
myEntity = MyEntity(name="홍길동")
save(myEntity)
}
}
728x90
반응형
'개발 > spring, spring boot' 카테고리의 다른 글
[Spring integration] TCP 연결 끊김 처리, connectionId (0) | 2024.06.25 |
---|---|
[Spring Integration] [tcp server] 역직렬화 처리 시 주의사항 (0) | 2024.06.17 |
[WebSocket] [STOMP] client 테스트 방법 (0) | 2024.06.11 |
[Spring Boot] [WebSocket] Protocol 설정 방법 (0) | 2024.02.20 |
[Spring Data JPA] Entity가 복합키를 사용할때 JpaRepository 개발 방법 (0) | 2024.02.16 |