Skip to content

[OPENJPA-3101] Add CDI support to AttributeConverter - #329

Open
cristof wants to merge 6 commits into
masterfrom
OPENJPA-3101
Open

cristof wants to merge 6 commits into
masterfrom
OPENJPA-3101

Conversation

@cristof

@cristof cristof commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

JPA 3.2 specification requires CDI support for EntityListeners and for AttributeConverters.
Building up the feature for AttributeConverters, I propose a more simple approach instead of duplicating code.
This implementations benefits and resolves also OPENJPA-3102, but in a more general and simpler (in my view) way.

* Builds up from OPENJPA-3089
* Moves initialization of BeanManager to own plugin, so it may be used by listeners and converters
* Defaults to no CDI usage, defined by property openjpa.CDISupport (none, listeners, converters, both)
* Added support of Jakarta EE container defined jakarta.persistence.bean.manager property
* Kept standalone configuration of EntityListenerFactory and ConverterFactory (remove it in favor of BMFactory?)
* CDI support is ruled by a single factory - BeanWrapperFactory
* Kept default stateless, non-CDI behavior for both EntityListener and AttributeConverter
* Added support of Jakarta EE bean manager variable (OPENJPA-3102)
* Updated documentation to reflect the new factory configuration

@rzo1 rzo1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, combining listeners and converters in one factory is a good direction, and taking over the jakarta.persistence.bean.manager handling from #328 works for me. A few things need to be fixed before this can go in, details inline:

  • the CDI factory caches are plain HashMaps again (thread safety),
  • converters now go through the factory on every conversion, and non-cacheable CDI converters are created per value,
  • spec 3.9: without CDI, converters that depend on injection must not be invoked,
  • javadoc of getConverterWrapper and the messages / docs for openjpa.CDISupport don't match the code.

Since this touches the configuration code and the converter path, please also run the TCK and the database builds on it before merging.

BeanWrapper<?> wrapper = null;
try {
return m.invoke(getConverterInstance(), val);
wrapper = getConverterWrapper(getConverter());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This runs for every value that is read or written. Before, the instance was cached in the field (volatile). Now every conversion goes through getRepository().getConfiguration().getBeanWrapperFactory() and a map lookup. For a converter that is not cacheable, CDIBeanWrapperFactory even creates the AnnotatedType, the InjectionTarget and a CreationalContext and runs the cacheability check for every single value.

A sketch:

// FieldMetaData
private transient volatile BeanWrapper<?> _converterWrapper;

private Object invokeConverter(Method m, Object val) {
    BeanWrapper<?> wrapper = _converterWrapper;
    if (wrapper == null) {
        wrapper = getConverterWrapper(getConverter());
        if (wrapper.cacheable()) {
            _converterWrapper = wrapper; // cleared again in setConverter()
        }
    }
    try {
        return m.invoke(wrapper.instance(), val);
    } ...
    } finally {
        if (!wrapper.cacheable()) {
            wrapper.dispose();
        }
    }
}

And in CDIBeanWrapperFactory, cache the InjectionTarget and the result of the cacheability check per class (e.g. a small record in a ConcurrentHashMap), so a non-cacheable converter only needs produce/inject/postConstruct per call.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added the code suggested and changed the way CDIBeanWrapperFactory works to keep a cache of injection target and creational context. The tests worked fine, but @rmannibucau review is really needed on that cache impl.


@SuppressWarnings("unchecked")
@Override
public <T> BeanWrapper<T> getConverterWrapper(Class<T> converterClass) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Spec 3.9 also says that in environments where CDI is not enabled, the provider must not invoke attribute converters that depend on CDI injection (that is point b) of OPENJPA-3101). Here a converter with @Inject fields is created with newInstance and invoked, and then fails with an NPE. The same happens in CDIBeanWrapperFactory when converters are not enabled or no BeanManager is there. Please check for injection points (fields, methods and constructors annotated with jakarta.inject.Inject, matched by name so the CDI API stays optional) and fail with a clear error instead of invoking the converter.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change would break current basecode. OpenJPA clients may already have code to deal with it, so I think that is better to keep current behavior (avoid discarding the listener or converter and failing startup).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this breaks existing code: a converter with an @Inject field cannot work today without CDI, it fails with an NPE on the first value. Spec 3.9 says the provider must not invoke it, so a clear error when the converter is set up is better than the NPE later. If you prefer not to fail, a warning at that point would be fine for me too, but it should not be silently invoked.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As a matter of fact, some listeners or converters may be implemented to deal with the null injected fields (falling back to a CDI.current() injection).
Implemented your suggestion by adding a configuration option of openjpa.CDISupport (strict), defaulting it to false to keep backwards compatibility.
When strict=true, it warns about the unavailability of the converter or listener.

};
setAliases(aliases);
setDefault(STATELESS_ALIAS);
setDefault(DISABLED_ALIAS);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a suggestion: when the container passes jakarta.persistence.bean.manager, CDI is enabled there (spec 9.1), so cdi could be the default in that case and none otherwise. Then TomEE and other containers get the spec behaviour without extra configuration, and Java SE stays as it is. Happy to discuss, not a blocker.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added default behavior suggested, pending approval of @rmannibucau on that. This may be a breaking change.

* Added default CDI enablement when property jakarta.persistence.bean.manager is et
* Added support to drop a cached bean
* Added cache of injection information in CDI environment
* Fixed messagens and manual information
@cristof

cristof commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@rmannibucau and @solomax , can we merge as is?

@solomax

solomax commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

Hello @cristof,
I never work woth CDI, so I'm not the right person to review this one :)
@rzo1, @rmannibucau could you please review? :))

@rzo1 rzo1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the updates. Most points from the first round are fixed: the caches are ConcurrentHashMaps again, FieldMetaData caches the wrapper, setConverter() drops it and the assertion is back, the Javadoc and the cdi-not-available message are fixed, and the unused messages are gone. TCK passed on the current head.

Still open:

  • CDIBeanWrapperFactory now shares one CreationalContext between all instances of a non-cacheable class. That leaks and releases dependents of other instances (inline).
  • isCacheable fails with an NPE when an injection point does not resolve (inline).
  • The fallback still logs only t.getMessage() (inline).
  • Docs: a broken cross reference and a typo; the new default (cdi when jakarta.persistence.bean.manager is passed) needs a note in the migration considerations (inline).
  • Spec 3.9 b) (converters that need injection without CDI): see my reply inline.

The Databases run on the current head was cancelled. Please run it again before merging.

* fixed possible NPE on bean resolve
* fixed resource leak by keeping CreationalContext in instance wrapper
* fixed trace logs
* updated and fixed documentation
@rzo1

rzo1 commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

@rmannibucau Can we have your CDI expertise? :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants