今日已更新 80 条资讯 | 累计 20052 条内容
关于我们

标签:#jpa

找到 1 篇相关文章

AI 资讯

🗄️ The JPA Enum Default Quietly Corrupts Your Data

You add an enum to an entity, slap @Enumerated on it, and move on. Five seconds. It is the kind of decision nobody writes a design doc for. Then six months later a row comes back as SHIPPED when it was PAID , no exception was thrown, no query failed, and you spend an afternoon learning that the default you never thought about has been silently rewriting history. Here is the order lifecycle we will use the whole way through: public enum OrderStatus { PENDING , PAID , SHIPPED , DELIVERED } Five ways to store it. They are not equivalent, and the gap between them only shows up under change. @Enumerated(ORDINAL): store the position This is the default. Leave the annotation bare and JPA stores the enum's ordinal, its index in the declaration order. @Enumerated ( EnumType . ORDINAL ) private OrderStatus status ; PENDING is 0, PAID is 1, SHIPPED is 2, DELIVERED is 3. The column is a tidy little smallint . Everything works. Until someone needs a new status and adds it where it reads well: public enum OrderStatus { PENDING , PAID , CANCELLED , // inserted here SHIPPED , DELIVERED } CANCELLED is now 2. SHIPPED is 3. DELIVERED is 4. Every row written before this change still holds the old integer, so every order that was SHIPPED (2) now reads back as CANCELLED . The database is correct. Your data is wrong. And nothing told you. If you are stuck with ORDINAL on a legacy schema, pin it with a test that fails the build the moment someone reorders: @Test void ordinalsAreFrozen () { assertEquals ( 0 , OrderStatus . PENDING . ordinal ()); assertEquals ( 1 , OrderStatus . PAID . ordinal ()); assertEquals ( 2 , OrderStatus . SHIPPED . ordinal ()); assertEquals ( 3 , OrderStatus . DELIVERED . ordinal ()); } New constants may only be appended. The test turns an invisible runtime corruption into a loud compile-time-ish failure. It is a guardrail, not a fix. @Enumerated(STRING): store the name Store the constant name instead of its position. @Enumerated ( EnumType . STRING ) private OrderS

2026-06-30 原文 →