Skip to content

Commit

Permalink
Fix foreign key exception test
Browse files Browse the repository at this point in the history
  • Loading branch information
louptheron committed Oct 13, 2023
1 parent 04f023d commit 6d5b0a1
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package fr.gouv.cacem.monitorenv.infrastructure.database.model
import com.fasterxml.jackson.annotation.JsonManagedReference
import fr.gouv.cacem.monitorenv.domain.entities.base.BaseEntity
import fr.gouv.cacem.monitorenv.domain.use_cases.base.dtos.FullBaseDTO
import fr.gouv.cacem.monitorenv.infrastructure.database.repositories.exceptions.ForeignKeyConstraintException
import jakarta.persistence.*
import org.hibernate.annotations.CreationTimestamp
import org.hibernate.annotations.UpdateTimestamp
Expand All @@ -18,7 +19,7 @@ data class BaseModel(

@OneToMany(fetch = FetchType.LAZY, mappedBy = "base")
@JsonManagedReference
val controlUnitResources: List<ControlUnitResourceModel>? = mutableListOf(),
val controlUnitResources: List<ControlUnitResourceModel> = listOf(),

@Column(name = "latitude", nullable = false)
val latitude: Double,
Expand Down Expand Up @@ -47,7 +48,7 @@ data class BaseModel(
): BaseModel {
return BaseModel(
id = base.id,
controlUnitResources = controlUnitResourceModels,
controlUnitResources = controlUnitResourceModels ?: listOf(),
latitude = base.latitude,
longitude = base.longitude,
name = base.name,
Expand All @@ -63,14 +64,23 @@ data class BaseModel(
): BaseModel {
return BaseModel(
id = fullBase.base.id,
controlUnitResources = controlUnitResourceModels,
controlUnitResources = controlUnitResourceModels ?: listOf(),
latitude = fullBase.base.latitude,
longitude = fullBase.base.longitude,
name = fullBase.base.name,
)
}
}

@PreRemove
fun checkControlUnitResourcesBeforeRemoval() {
if (controlUnitResources.isNotEmpty()) {
throw ForeignKeyConstraintException(
"Cannot delete base (ID=$id) due to existing relationships.",
)
}
}

fun toBase(): BaseEntity {
return BaseEntity(
id,
Expand All @@ -83,7 +93,7 @@ data class BaseModel(
fun toFullBase(): FullBaseDTO {
return FullBaseDTO(
base = toBase(),
controlUnitResources = requireNotNull(controlUnitResources).map { it.toControlUnitResource() },
controlUnitResources = controlUnitResources.map { it.toControlUnitResource() },
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,6 @@ class JpaBaseRepository(
private val dbBaseRepository: IDBBaseRepository,
) : IBaseRepository {
override fun deleteById(baseId: Int) {
val fullBase = findById(baseId)
// println(fullBase.controlUnitResources)
/*if (fullBase.controlUnitResources.isNotEmpty()) {
throw ForeignKeyConstraintException(
"Cannot delete base (ID=$baseId) due to existing relationships.",
)
}*/

dbBaseRepository.deleteById(baseId)
}

Expand Down

0 comments on commit 6d5b0a1

Please sign in to comment.