1
16 package org.springframework.data.jpa.repository.support;
17
18 import java.util.List;
19 import java.util.Set;
20
21 import javax.persistence.EntityManager;
22 import javax.persistence.metamodel.ManagedType;
23
24 import org.springframework.data.jpa.repository.JpaContext;
25 import org.springframework.util.Assert;
26 import org.springframework.util.LinkedMultiValueMap;
27 import org.springframework.util.MultiValueMap;
28
29
36 public class DefaultJpaContext implements JpaContext {
37
38 private final MultiValueMap<Class<?>, EntityManager> entityManagers;
39
40
45 public DefaultJpaContext(Set<EntityManager> entityManagers) {
46
47 Assert.notNull(entityManagers, "EntityManagers must not be null!");
48 Assert.notEmpty(entityManagers, "EntityManagers must not be empty!");
49
50 this.entityManagers = new LinkedMultiValueMap<Class<?>, EntityManager>();
51
52 for (EntityManager em : entityManagers) {
53 for (ManagedType<?> managedType : em.getMetamodel().getManagedTypes()) {
54 this.entityManagers.add(managedType.getJavaType(), em);
55 }
56 }
57 }
58
59
63 @Override
64 public EntityManager getEntityManagerByManagedType(Class<?> type) {
65
66 Assert.notNull(type, "Type must not be null!");
67
68 if (!entityManagers.containsKey(type)) {
69 throw new IllegalArgumentException(String.format("%s is not a managed type!", type));
70 }
71
72 List<EntityManager> candidates = this.entityManagers.get(type);
73
74 if (candidates.size() == 1) {
75 return candidates.get(0);
76 }
77
78 throw new IllegalArgumentException(
79 String.format("%s managed by more than one EntityManagers: %s!", type.getName(), candidates));
80 }
81 }
82