11package io .teaql .core .meta ;
22
3- import io .teaql .core .BaseEntity ;
43import io .teaql .core .Entity ;
4+ import io .teaql .core .UserContext ;
5+ import java .util .Objects ;
56
67/**
78 * Centralized factory for entity creation.
@@ -31,19 +32,19 @@ public interface EntityFactory {
3132 */
3233 <T extends Entity > T createEntity (EntityDescriptor descriptor );
3334
34- /**
35- * Default implementation that delegates to EntityDescriptor.createEntity()
36- */
35+ /** Creates an entity factory bound to the invoking runtime's metadata. */
36+ static EntityFactory forContext (UserContext context ) {
37+ return forMetadata (EntityMetaFactory .requireFrom (context ));
38+ }
39+
40+ /** Creates an entity factory bound to an explicit metadata snapshot. */
3741 @ SuppressWarnings ("unchecked" )
38- static EntityFactory defaultFactory () {
42+ static EntityFactory forMetadata (EntityMetaFactory metadata ) {
43+ Objects .requireNonNull (metadata , "metadata must not be null" );
3944 return new EntityFactory () {
4045 @ Override
4146 public <T extends Entity > T createEntity (Class <T > entityType ) {
42- EntityMetaFactory metaFactory = EntityMetaFactory .get ();
43- if (metaFactory == null ) {
44- throw new IllegalStateException ("EntityMetaFactory not initialized" );
45- }
46- for (EntityDescriptor descriptor : metaFactory .allEntityDescriptors ()) {
47+ for (EntityDescriptor descriptor : metadata .allEntityDescriptors ()) {
4748 if (descriptor .getTargetType () == entityType ) {
4849 return (T ) descriptor .createEntity ();
4950 }
@@ -53,7 +54,7 @@ public <T extends Entity> T createEntity(Class<T> entityType) {
5354
5455 @ Override
5556 public Entity createEntity (String typeName ) {
56- EntityDescriptor descriptor = EntityMetaFactory . get () .resolveEntityDescriptor (typeName );
57+ EntityDescriptor descriptor = metadata .resolveEntityDescriptor (typeName );
5758 if (descriptor == null ) {
5859 throw new IllegalArgumentException ("No entity descriptor registered for " + typeName );
5960 }
@@ -66,4 +67,18 @@ public <T extends Entity> T createEntity(EntityDescriptor descriptor) {
6667 }
6768 };
6869 }
70+
71+ /**
72+ * Legacy process-global factory. Prefer {@link #forContext(UserContext)} so
73+ * two runtimes in one process cannot silently share entity metadata.
74+ */
75+ @ Deprecated
76+ static EntityFactory defaultFactory () {
77+ EntityMetaFactory metadata = EntityMetaFactory .get ();
78+ if (metadata == null ) {
79+ throw new IllegalStateException ("Global EntityMetaFactory is not initialized; "
80+ + "use EntityFactory.forContext(context)" );
81+ }
82+ return forMetadata (metadata );
83+ }
6984}
0 commit comments