iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔖

Compatibility Issues and JSON-B Implementation Encountered During Payara Migration

に公開
2025/12/08

Compatibility Issues and JSON-B Implementation Faced During Payara Migration

Introduction

During the migration from GlassFish 4.1 to Payara 6.11, the most challenging aspects were Jakarta EE compliance and date type serialization issues.

This article outlines the compatibility issues encountered during the Payara migration and how they were resolved using custom serializers and deserializers.

Issues Encountered

Issue 1: Migration from Java EE to Jakarta EE

In Payara 6.11, migrating from Java EE to Jakarta EE is mandatory. With the transition from GlassFish 4.1 + Java 8 to Payara 6.11 + Java 21, package names had to be updated.

Changes:

  • javax.servlet.* → jakarta.servlet.*
  • javax.persistence.* → jakarta.persistence.*
  • javax.ws.rs.* → jakarta.ws.rs.*

Issue 2: Change in ZonedDateTime Output Format

After migrating to Payara, the JSON output format for ZonedDateTime changed.

Before (GlassFish):

{
  "createdAt": "2024-01-15T10:30:00Z"
}

After (Payara):

{
  "createdAt": "2024-01-15T10:30:00Z[UTC]"
}

The [UTC] suffix caused issues. The existing VB client could not recognize it as a date type, resulting in errors.

Issue 3: Empty String Deserialization Error

Empty strings, which were accepted in GlassFish, strictly resulted in errors in Payara.

GlassFish:

{
  "statusChangedDate": ""
}

↓ Automatically treated as null

Payara:

{
  "statusChangedDate": ""
}

↓ Deserialization error occurs

Issue 3.1: Sending Empty Strings to Numeric Fields (shotCount / disposedShotCount)

Beyond dates, sending empty strings to numeric fields also caused issues because JSON-B has become stricter. Cases that "just happened to work" in GlassFish resulted in exceptions in Payara.

The exceptions that occurred were as follows:

Caused by: jakarta.json.bind.JsonbException: Unable to deserialize property 'disposedShotCount' because of: Error deserialize JSON value into type: int.
Caused by: java.lang.NumberFormatException: For input string: ""

The cause was that the request JSON looked like this:

"shotCount": "0",
"disposedShotCount": ""

Since the server-side entity is defined as a primitive numeric type like int disposedShotCount;:

  • "0" → Parsable as int, so it is OK.
  • "" → Cannot be parsed as int, resulting in NumberFormatException.

JSON-B (Yasson) failed to deserialize, leading to 400/500 series errors.

Strategy: "Send numbers as numbers from the start"

We decided to "align the client-side (VB) type definition with the server-side."

Before (VB side)

Property shotCount As String = "0"
Property disposedShotCount As String = "0"

After (VB side)

Property shotCount As Integer
Property disposedShotCount As Integer

Since VB.NET Integer defaults to 0 when not assigned, even without an assignment, it is serialized as a numeric literal in JSON:

"shotCount": 0,
"disposedShotCount": 0

This prevents "" (empty strings) from being sent and allows deserialization to int to complete successfully.

Alternatives Considered

There are options to handle this on the server side:

  • Change the entity from int to Integer to allow null, and use a custom deserializer to convert "" to null.
  • Accept it as String disposedShotCount and map the empty string to 0 or null on the application side when calling Integer.parseInt.

However, the structure where "database columns and Java fields are numeric, but client convenience forces mixed strings" is technical debt. In this case, we concluded that the simplest and most maintainable approach is:

Send numbers as numbers from the client side.

Lessons learned from this incident (Numeric version)

  • "Sending empty strings to numeric fields also causes strict errors in Payara / JSON-B, not just for dates."
  • "Ambiguous specifications that treat "" as 'effectively 0' or 'effectively null' will always explode during middleware upgrades."
  • "Database, Java, and client types should be aligned as much as possible, moving towards a world of 'Numbers as numbers, nulls as nulls.'"

In the GlassFish 4.1 era, things "just happened to work," but in Payara 6, the consequences surfaced all at once. Through this experience, I realized the importance of properly designing type and representation (JSON) mappings from the beginning.

Issue 4: Serialization Exception due to Collection Element Type Mismatch

When a field defined as List<String> actually contained List<Integer>, it was implicitly converted to strings during serialization in GlassFish. However, in Payara 6 (Jakarta EE 10), type checking became strict, resulting in a ClassCastException and failure to generate the response.

Exception:
JsonbException: Unable to serialize property 'departmentIds' ... Caused by: java.lang.ClassCastException

Solving the Issues

Step 1: Bulk Replacement from Java EE to Jakarta EE

First, we performed a bulk replacement of package names.

# Bulk replace javax.* with jakarta.*
find src -name "*.java" -type f -exec sed -i 's/import javax\./import jakarta./g' {} \;

Main target packages:

  • javax.servlet.* → jakarta.servlet.*
  • javax.persistence.* → jakarta.persistence.*
  • javax.ws.rs.* → jakarta.ws.rs.*
  • javax.json.* → jakarta.json.*
  • javax.validation.* → jakarta.validation.*

Notes:

  • Do not replace javax.xml.* etc., as they are not part of Jakarta EE.
  • Library dependencies must also be updated to the Jakarta EE-compatible versions.

Step 2: Implementing Custom Serializers

To standardize the date output format, we implemented three custom serializers.

1. Serializer for ZonedDateTime

// UtcZonedDateTimeSerializer.java
package com.kmcj.karte.config;

import java.time.ZonedDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import jakarta.json.bind.serializer.JsonbSerializer;
import jakarta.json.bind.serializer.SerializationContext;
import jakarta.json.stream.JsonGenerator;

/**
 * Serializer that normalizes ZonedDateTime to UTC and outputs it in ISO 8601 (fixed with Z at the end).
 * Purpose: Eliminating the "Z[UTC]" format after the Payara upgrade.
 */
public class UtcZonedDateTimeSerializer implements JsonbSerializer<ZonedDateTime> {
    @Override
    public void serialize(ZonedDateTime value, JsonGenerator generator, SerializationContext ctx) {
        if (value == null) {
            generator.writeNull();
            return;
        }
        // Convert ZonedDateTime to UTC, then to Date
        Date utcDate = Date.from(value.withZoneSameInstant(ZoneOffset.UTC).toInstant());
        // Delegate to Date serializer to unify the format
        ctx.serialize(utcDate, generator);
    }
}
  • Normalize to UTC with withZoneSameInstant(ZoneOffset.UTC)
  • Convert to Date to leverage existing date format settings
  • Centralize format management by delegating with ctx.serialize()

2. Serializer for OffsetDateTime

// UtcOffsetDateTimeSerializer.java
package com.kmcj.karte.config;

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import jakarta.json.bind.serializer.JsonbSerializer;
import jakarta.json.bind.serializer.SerializationContext;
import jakarta.json.stream.JsonGenerator;

/**
 * Serializer that normalizes OffsetDateTime to UTC and outputs it in ISO 8601 (fixed with Z at the end).
 */
public class UtcOffsetDateTimeSerializer implements JsonbSerializer<OffsetDateTime> {
    @Override
    public void serialize(OffsetDateTime value, JsonGenerator generator, SerializationContext ctx) {
        if (value == null) {
            generator.writeNull();
            return;
        }
        Date utcDate = Date.from(value.withOffsetSameInstant(ZoneOffset.UTC).toInstant());
        ctx.serialize(utcDate, generator);
    }
}
  • Similarly, normalize OffsetDateTime to UTC
  • Use withOffsetSameInstant(ZoneOffset.UTC) to convert the offset to UTC

3. Serializer for Date

// UtcDateSerializer.java
package com.kmcj.karte.config;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import jakarta.json.bind.serializer.JsonbSerializer;
import jakarta.json.bind.serializer.SerializationContext;
import jakarta.json.stream.JsonGenerator;

/**
 * Serializer that outputs java.util.Date in UTC ISO 8601 format (fixed with Z at the end).
 */
public class UtcDateSerializer implements JsonbSerializer<Date> {
    private static final ThreadLocal<SimpleDateFormat> FORMATTER = ThreadLocal.withInitial(() -> {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        return sdf;
    });

    @Override
    public void serialize(Date date, JsonGenerator generator, SerializationContext serializationContext) {
        if (date == null) {
            generator.writeNull();
            return;
        }
        generator.write(FORMATTER.get().format(date));
    }
}
  • Use ThreadLocal for thread safety
  • Manage SimpleDateFormat via ThreadLocal because it is not thread-safe
  • Explicitly set the timezone to UTC

Step 3: Registering the Serializers

We created a JSON-B configuration provider to register the custom serializers.

// JsonbConfigProvider.java
package com.kmcj.karte.config;

import java.util.Locale;
import jakarta.json.bind.Jsonb;
import jakarta.json.bind.JsonbBuilder;
import jakarta.json.bind.JsonbConfig;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.ext.ContextResolver;
import jakarta.ws.rs.ext.Provider;

/**
 * Fixes the global date-time format for JSON-B to ISO 8601 (fixed with Z, no timezone ID).
 * Prevents date conversion errors on the VB side caused by ZonedDateTime outputting "Z[UTC]" after the Payara upgrade.
 */
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JsonbConfigProvider implements ContextResolver<Jsonb> {
    private final Jsonb jsonb;

    public JsonbConfigProvider() {
        JsonbConfig config = new JsonbConfig()
                .withDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US)
                .withSerializers(
                        new UtcDateSerializer(),
                        new UtcOffsetDateTimeSerializer(),
                        new UtcZonedDateTimeSerializer()
                );
        this.jsonb = JsonbBuilder.create(config);
    }

    @Override
    public Jsonb getContext(Class<?> type) {
        return jsonb;
    }
}
  • Registered with JAX-RS using the @Provider annotation
  • Applied to JSON with @Produces(MediaType.APPLICATION_JSON)
  • Implemented ContextResolver<Jsonb> to provide JSON-B settings

Step 3.5: Pitfalls of JSON-B Date Formatting and Final Design

During the migration to Payara, I ran into two major issues regarding JSON-B date formatting.

1. Making withDateFormat too restrictive broke existing data

Initially, I configured the JsonbConfigProvider as follows:

.withDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US)

This specifies a format that only permits strings without milliseconds and with a fixed 'Z' at the end, such as 2025-08-30T15:00:00Z.

However, the actual JSON data contained values like:

  • 2025-08-30T15:00:00.000Z (Web side, includes milliseconds)
  • 2025-12-08T16:24:47 (Tablet side, no 'Z')

This caused deserialization errors for fields bound to java.util.Date.

To fix this, I expanded the format for java.util.Date / Calendar to accommodate both presence and absence of milliseconds and timezones.

// JsonbConfigProvider.java (excerpt)
JsonbConfig config = new JsonbConfig()
        // For java.util.Date / Calendar
        // Examples:
        //   2025-08-30T15:00:00
        //   2025-08-30T15:00:00.000Z
        //   2025-08-30T15:00:00+09:00
        .withDateFormat("yyyy-MM-dd'T'HH:mm:ss[.SSS][X]", Locale.JAPAN)
        .withSerializers(
                new UtcDateSerializer(),
                new UtcOffsetDateTimeSerializer(),
                new UtcZonedDateTimeSerializer()
        )
        .withDeserializers(
                new UtcZonedDateTimeDeserializer() // Support for ZonedDateTime input (handling missing Z)
        );

The [.SSS][X] used here represents optional elements:

  • .SSS ... milliseconds are optional.
  • X ... timezone (e.g., Z, +09:00) is optional.

2. The issue where withDateFormat does not apply to java.time.*

Another issue was that withDateFormat does not affect java.time.* types.

  • withDateFormat(...) primarily affects java.util.Date / java.util.Calendar.
  • Types like ZonedDateTime / OffsetDateTime / LocalDateTime are parsed using the standard format of DateTimeFormatter by default.

Consequently, for entities holding ZonedDateTime fields:

  • 2025-12-08T16:24:47Z or values with +09:00 → Worked fine.
  • 2025-12-08T16:24:47 (no 'Z' from tablet) → ZonedDateTime.parse(..., ISO_ZONED_DATE_TIME) failed, resulting in DateTimeParseException.

To address this, I added a custom deserializer for ZonedDateTime.

// UtcZonedDateTimeDeserializer.java
package com.kmcj.karte.config;

import jakarta.json.bind.serializer.DeserializationContext;
import jakarta.json.bind.serializer.JsonbDeserializer;
import jakarta.json.stream.JsonParser;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 * Deserializer for ZonedDateTime.
 * Accepts the following formats:
 * 1. ISO_ZONED_DATE_TIME (e.g., "2025-12-08T16:24:47Z", "2025-12-08T16:24:47+09:00")
 * 2. ISO_LOCAL_DATE_TIME (e.g., "2025-12-08T16:24:47") -> Assigns system default timezone
 */
public class UtcZonedDateTimeDeserializer implements JsonbDeserializer00ZonedDateTime00 {

    @Override
    public ZonedDateTime deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) {
        String dateStr = parser.getString();

        // 1. If timezone is present (Z or +09:00), parse with standard ISO_ZONED_DATE_TIME
        try {
            return ZonedDateTime.parse(dateStr, DateTimeFormatter.ISO_ZONED_DATE_TIME);
        } catch (DateTimeParseException e) {
            // Fall through
        }

        // 2. If no timezone, read as ISO_LOCAL_DATE_TIME and assign system default zone (Asia/Tokyo)
        try {
            LocalDateTime ldt = LocalDateTime.parse(dateStr, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
            return ldt.atZone(ZoneId.systemDefault());
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("Failed to parse ZonedDateTime: " + dateStr, e);
        }
    }
}

3. Final Strategy

Based on these trials, the strategy is:

  • Keep the reception side for java.util.Date / Calendar slightly flexible for backward compatibility.
  • Prepare dedicated Serializer / Deserializer pairs for java.time.* types to explicitly define handling logic.
  • Gradually tighten the accepted format range once client-side (VB / Web / Tablet) code stabilizes.

I realized the importance of being aware of the differences in handling java.util.Date and java.time.* instead of relying solely on global JSON-B configuration.

Supplement: Why "ISO 8601 with Z" is Modern, and the Gap with Legacy Clients

Throughout this migration, I acutely felt the gap between the "world that assumes ISO 8601 with Z" and the "legacy world that assumes local time."

The Meaning and Modern Handling of 'Z'

The 'Z' at the end of 2025-08-30T15:00:00.000Z is an ISO 8601 symbol representing UTC (Coordinated Universal Time, +00:00), meaning the same as +00:00.

2025-08-30T15:00:00.000Z  ≒  2025-08-30T15:00:00.000+00:00

Modern REST / JSON APIs are generally designed with the following premises:

  • UTC-based to avoid time difference issues between servers and clients.
  • Written in ISO 8601 (yyyy-MM-dd'T'HH:mm:ss.SSSX).
  • Timezone specified as Z or an offset like +09:00.

"ISO 8601 with Z" has become the practical standard.

On the other hand, strings with absolutely no timezone information, such as 2025-12-08T16:24:47,

  • Make it impossible to know "what timezone this time belongs to."
  • Force the server to guess whether it is local or UTC.
  • Easily lead to accidents like 9-hour discrepancies or off-by-one date errors.

The Gap with Tablet Apps from the VS2010 Era

In this environment:

  • The Web side (Browser/JavaScript) used UTC + ISO 8601 format, like 2025-08-30T15:00:00.000Z.
  • The Tablet side (VB / .NET 4.0 / Visual Studio 2010) sent local datetime strings without timezones, like 2025-12-08T16:24:47.

In .NET / VB from the VS2010 era:

  • Code often did not account for the Kind (Local, Utc, Unspecified) of DateTime.
  • Implementations that serialized local time directly using ToString("yyyy-MM-ddTHH:mm:ss") were common.
  • API designs assuming timezones or UTC were not mainstream.

This background caused a sudden conflict with the modern server implementation (JSON-B / java.time.*) that assumes "ISO 8601 with Z."

Current Policy

I settled on the following policy:

  • Ideally, the API should standardize on "ISO 8601 with Z (UTC)."

    • Example: yyyy-MM-dd'T'HH:mm:ss.SSSX for 2025-08-30T15:00:00.000Z.
  • However, due to constraints like legacy VS2010 tablets:

    • For java.util.Date, allow a wider range of formats on the receiving end, using yyyy-MM-dd'T'HH:mm:ss[.SSS][X].
    • Use a custom deserializer for ZonedDateTime to interpret and absorb Z-present, offset-present, and Z-absent local datetime formats in stages.
  • Once clients (VB / Web / Tablet) are updated sequentially:

    • Gradually converge the server's accepted format range to "ISO 8601 with Z."

In short, this is a compromise: "Moving toward a world that assumes ISO 8601 with Z in the long term, while handling the 'local datetime culture' of legacy clients on the server side for now." My implementation of JsonbConfig + custom Serializer/Deserializer was built for this purpose.

Step 4: Registration in ApplicationConfig

Register the provider in the JAX-RS ApplicationConfig.

// ApplicationConfig.java (partial excerpt)
@jakarta.ws.rs.ApplicationPath("api")
public class ApplicationConfig extends Application {
    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new java.util.HashSet<>();
        addRestResourceClasses(resources);
        resources.add(MultiPartFeature.class);
        // Register custom JSON-B configuration
        resources.add(com.kmcj.karte.config.JsonbConfigProvider.class);
        return resources;
    }
}

Step 5: Implementation of Custom Deserializer

To safely handle empty strings as null, I implemented a custom deserializer.

// EmptyToNullDateDeserializer.java
package com.kmcj.karte.util;

import jakarta.json.bind.serializer.JsonbDeserializer;
import jakarta.json.bind.serializer.DeserializationContext;
import jakarta.json.stream.JsonParser;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;

/**
 * Date deserializer for JSON-B that safely converts empty strings or nulls to null,
 * while allowing variations in received formats.
 */
public class EmptyToNullDateDeserializer implements JsonbDeserializer<Date> {
    @Override
    public Date deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) {
        String text = parser.getString();
        
        // Treat empty strings or null as null
        if (text == null || text.isBlank()) {
            return null;
        }

        // Try parsing as OffsetDateTime -> ISO Date -> Slash-separated Date
        try {
            return Date.from(OffsetDateTime.parse(text).toInstant());
        } catch (DateTimeParseException ignored) {
            // Fall through
        }

        for (DateTimeFormatter formatter : new DateTimeFormatter[]{
                DateTimeFormatter.ISO_LOCAL_DATE,
                DateTimeFormatter.ofPattern("yyyy/MM/dd")
        }) {
            try {
                LocalDate localDate = LocalDate.parse(text, formatter);
                return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
            } catch (DateTimeParseException ignored) {
                // Try next
            }
        }

        throw new DateTimeParseException("Unsupported date format", text, 0);
    }
}
  • Used isBlank() to detect empty strings (more rigorous than isEmpty()).
  • Attempted multiple formats to ensure flexibility.
  • Explicitly throws an error for unsupported formats.

Step 6: Application to Entities

Apply the custom deserializer to entity fields.

// MstMold.java (partial excerpt)
@Entity
@Table(name = "mst_mold")
public class MstMold implements Serializable {
    
    @JsonbTypeDeserializer(EmptyToNullDateDeserializer.class)
    @Column(name = "STATUS_CHANGED_DATE")
    @Temporal(TemporalType.DATE)
    private Date statusChangedDate;
    
    // Other fields...
}
  • Applied per-field using @JsonbTypeDeserializer.
  • Global configuration is also possible if it needs to be applied to all Date fields.

Step 7: Explicit Type Conversion via Object Mapping

I fixed areas where JPQL was used to fetch a list of IDs (Integer) and forced them into a List<String> field. I corrected this by fetching the list of related entities (objects) first, extracting the ID, and explicitly converting it to String to ensure type safety.

Before:

// Returned List<Integer>, but received in a List<String> variable (with warnings)
List<String> ids = entityManager.createNamedQuery("RelatedEntity.findIdsByParentId")
        .setParameter("parentId", parentEntity.getId())
        .getResultList();
parentEntity.setChildIds(ids); // A list of Integer is set at runtime

After:

// Fetch as a list of entities first
List<RelatedEntity> relatedEntities = entityManager
        .createNamedQuery("RelatedEntity.findByParentId", RelatedEntity.class)
        .setParameter("parentId", parentEntity.getId())
        .getResultList();

// Extract as Integer and explicitly convert to String
List<String> childIds = relatedEntities.stream()
        .map(e -> e.getChildId()) // Get Integer
        .map(String::valueOf) // Convert to String
        .collect(Collectors.toList());

parentEntity.setChildIds(childIds);

Verification

Serialization (Response) Check

Before:

{
  "createdAt": "2024-01-15T10:30:00Z[UTC]"
}

After:

{
  "createdAt": "2024-01-15T10:30:00Z"
}

VB client now correctly recognizes it as a date type.

Deserialization (Request) Check

GlassFish:

{
  "statusChangedDate": ""
}

Automatically handled as null.

Payara (Before fix):

{
  "statusChangedDate": ""
}

Deserialization error occurred.

Payara (After fix):

{
  "statusChangedDate": ""
}

Safely processed as null.

Implementation Notes

1. Use of ThreadLocal

Since SimpleDateFormat is not thread-safe, it must be managed with ThreadLocal.

private static final ThreadLocal<SimpleDateFormat> FORMATTER = ThreadLocal.withInitial(() -> {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    return sdf;
});

2. Timezone Standardization

Normalize all dates to UTC to avoid timezone issues.

Date utcDate = Date.from(value.withZoneSameInstant(ZoneOffset.UTC).toInstant());

3. Thorough Null Checks

Always perform a null check in serializers and deserializers.

if (value == null) {
    generator.writeNull();
    return;
}

Performance Impact

Overhead of ThreadLocal

Because ThreadLocal is used, a SimpleDateFormat instance is created per thread.

Measurement:

  • Normal response: 50ms average
  • After applying custom serializer: 52ms average (+2ms)

This is at an acceptable level for practical use.

Alternative Considerations

java.time.format.DateTimeFormatter is thread-safe, making ThreadLocal unnecessary.

private static final DateTimeFormatter FORMATTER = 
    DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
                     .withZone(ZoneId.of("UTC"));

However, since you cannot format Date directly, you must first convert it to an Instant.

Troubleshooting

Problem: Custom serializer is not applied

Cause:
JsonbConfigProvider is not registered in ApplicationConfig.

Solution:

resources.add(com.kmcj.karte.config.JsonbConfigProvider.class);

Problem: Some fields are still output in the old format

Cause:
There is a type for which the serializer is not registered.

Solution:
Register serializers for all required types.

.withSerializers(
    new UtcDateSerializer(),
    new UtcOffsetDateTimeSerializer(),
    new UtcZonedDateTimeSerializer()
)

Problem: Deserialization error occurs

Cause:
Deserializer is not applied to the entity.

Solution:

@JsonbTypeDeserializer(EmptyToNullDateDeserializer.class)
private Date statusChangedDate;

Lessons Learned: Avoiding Type Mismatches

The root cause of the ClassCastException was that the DB column definition and the entity (especially @Transient fields) type definitions did not match.

While the DB column was defined as INT, the entity provided a List<String> field with @Transient for the convenience of JSON response display. During the GlassFish 4.1 (Java EE 7) era, JSON-B (EclipseLink MOXy, etc.) implicitly handled type conversion when fetching a List<Integer> from the DB and setting it to this List<String> field, so it worked on the surface.

However, with the stricter specifications in the migration to Payara 6 (Jakarta EE 10), this practice of "forcing a mismatching type" was no longer allowed, resulting in ClassCastException.

Lessons:

  • Do not let the backend be influenced by display data types: Do not bring front-end display requirements (like wanting a String) into the backend data structure (where the DB is an Integer).
  • Always match DB and Java types: If the DB is numeric, treat it as numeric in Java.
  • Do not rely on implicit type conversion: Expecting the framework to handle it will become debt during future migrations.

I realized that constant awareness of whether "it is defined with the correct type and correctly mapped"—rather than just "it works, so it's fine"—is the shortest path to preventing future trouble.

Summary

I explained the compatibility issues faced during the Payara migration and the custom serializers/deserializers implemented as solutions.

Key Points:

  • Handled the transition to Jakarta EE via global package name replacement.
  • Normalized output to UTC to avoid timezone issues.
  • Handled deserialization of empty strings via custom deserializer.
  • Ensured thread safety using ThreadLocal.

This allowed the migration from GlassFish 4.1 to Payara 6.11 while maintaining compatibility with the legacy VB client.

Discussion