下面列出了怎么用javax.persistence.metamodel.EntityType的API类实例代码及写法,或者点击链接到github查看源代码。
public List<Movie> getMovies(Integer firstResult, Integer maxResults, String field, String searchTerm) {
CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Movie> cq = qb.createQuery(Movie.class);
Root<Movie> root = cq.from(Movie.class);
EntityType<Movie> type = entityManager.getMetamodel().entity(Movie.class);
if (field != null && searchTerm != null && !"".equals(field.trim()) && !"".equals(searchTerm.trim())) {
Path<String> path = root.get(type.getDeclaredSingularAttribute(field.trim(), String.class));
Predicate condition = qb.like(path, "%" + searchTerm.trim() + "%");
cq.where(condition);
}
TypedQuery<Movie> q = entityManager.createQuery(cq);
if (maxResults != null) {
q.setMaxResults(maxResults);
}
if (firstResult != null) {
q.setFirstResult(firstResult);
}
return q.getResultList();
}
/**
* {@inheritDoc}
*/
@Override
protected synchronized void initializeMetadata(Collection<Class<?>> types) {
LOG.info("Initializing JPA Metadata from " + entityManager);
masterMetadataMap.clear();
// QUESTION: When is JPA loaded so this service can initialize itself?
// Build and store the map
for ( IdentifiableType<?> identifiableType : entityManager.getMetamodel().getEntities() ) {
//Only extract the metadata if EntityType and not a MappedSuperClass
if(identifiableType instanceof EntityType<?>){
EntityType<?> type = (EntityType<?>)identifiableType;
try {
masterMetadataMap.put(type.getBindableJavaType(), getMetadataForClass(type.getBindableJavaType()));
if (LOG.isDebugEnabled()) {
LOG.debug("Added Metadata For: " + type.getBindableJavaType());
}
} catch (Exception ex) {
LOG.error("Error obtaining JPA metadata for type: " + type.getJavaType(), ex);
}
}
}
}
/**
* Gets a single field's relationship metadata.
*
* @param rd The singular attribute to process.
* @return The single field's relationship metadata.
*/
protected DataObjectRelationship getRelationshipMetadata(SingularAttribute rd) {
try {
DataObjectRelationshipImpl relationship = new DataObjectRelationshipImpl();
// OJB stores the related class object name. We need to go into the repository and grab the table name.
Class<?> referencedClass = rd.getBindableJavaType();
EntityType<?> referencedEntityType = entityManager.getMetamodel().entity(referencedClass);
relationship.setName(rd.getName());
relationship.setRelatedType(referencedClass);
populateImplementationSpecificRelationshipLevelMetadata(relationship, rd);
return relationship;
} catch (RuntimeException ex) {
LOG.error("Unable to process Relationship metadata: " + rd);
throw ex;
}
}
@Override
@SuppressWarnings("unchecked")
public <T> List<EntityGraph<? super T>> findEntityGraphsByType(Class<T> entityClass) {
final EntityType<T> entityType = entity( entityClass );
if ( entityType == null ) {
throw new IllegalArgumentException( "Given class is not an entity : " + entityClass.getName() );
}
final List<EntityGraph<? super T>> results = new ArrayList<>();
for ( EntityGraph entityGraph : entityGraphMap.values() ) {
if ( !EntityGraphImplementor.class.isInstance( entityGraph ) ) {
continue;
}
final EntityGraphImplementor egi = (EntityGraphImplementor) entityGraph;
if ( egi.appliesTo( entityType ) ) {
results.add( egi );
}
}
return results;
}
private synchronized Integer getPKValue(EntityType targetEntity, String keyColumn, EntityManager entityManager) {
logger.debug("IN");
Integer toReturn = 0;
String name = targetEntity.getName();
logger.debug("SELECT max(p." + keyColumn + ") as c FROM " + targetEntity.getName() + " p");
// logger.debug("SELECT max(p."+keyColumn+") as c FROM "+targetEntity.getName()+" p");
Query maxQuery = entityManager.createQuery("SELECT max(p." + keyColumn + ") as c FROM " + targetEntity.getName() + " p");
Object result = maxQuery.getSingleResult();
if (result != null) {
toReturn = Integer.valueOf(result.toString());
toReturn++;
}
logger.debug("New PK is " + toReturn);
logger.debug("OUT");
return toReturn;
}
public EntityType getTargetEntity(RegistryConfiguration registryConf, EntityManager entityManager) {
EntityType targetEntity;
String targetEntityName = getTargetEntityName(registryConf);
Metamodel classMetadata = entityManager.getMetamodel();
Iterator it = classMetadata.getEntities().iterator();
targetEntity = null;
while (it.hasNext()) {
EntityType entity = (EntityType) it.next();
String jpaEntityName = entity.getName();
if (entity != null && jpaEntityName.equals(targetEntityName)) {
targetEntity = entity;
break;
}
}
return targetEntity;
}
private void addRootEntities(ModelStructure modelStructure) {
Metamodel jpaMetamodel;
Set<EntityType<?>> jpaEntities;
String modelName = getDataSource().getConfiguration().getModelName();
jpaMetamodel = getEntityManager().getMetamodel();
jpaEntities = jpaMetamodel.getEntities();
logger.debug("Jpa metamodel contains [" + jpaEntities.size() + "] entity types");
for (EntityType<?> entityType : jpaEntities) {
logger.debug("Adding entity type [" + entityType + "] to model structure");
String entityTypeName = entityType.getJavaType().getName();
addEntity(modelStructure, modelName, entityTypeName);
logger.info("Entity type [" + entityType + "] succesfully added to model structure");
}
}
@Override
public void startUp(ServletContext servletContext) {
try {
initializeJPA();
} catch (PersistenceException e) {
//fix for MCR-1236
if (MCRConfiguration2.getBoolean("MCR.Persistence.Database.Enable").orElse(true)) {
LogManager.getLogger()
.error(() -> "Could not initialize JPA. Database access is disabled in this session.", e);
MCRConfiguration2.set("MCR.Persistence.Database.Enable", String.valueOf(false));
}
MCREntityManagerProvider.init(e);
return;
}
Metamodel metamodel = MCREntityManagerProvider.getEntityManagerFactory().getMetamodel();
checkHibernateMappingConfig(metamodel);
LogManager.getLogger()
.info("Mapping these entities: {}", metamodel.getEntities()
.stream()
.map(EntityType::getJavaType)
.map(Class::getName)
.collect(Collectors.toList()));
MCRShutdownHandler.getInstance().addCloseable(new MCRJPAShutdownProcessor());
}
@Bean
public CacheManager cacheManager() {
log.debug("Starting Ehcache");
cacheManager = net.sf.ehcache.CacheManager.create();
cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
log.debug("Registering Ehcache Metrics gauges");
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
String name = entity.getName();
if (name == null || entity.getJavaType() != null) {
name = entity.getJavaType().getName();
}
Assert.notNull(name, "entity cannot exist without a identifier");
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L));
net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
}
}
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}
@Bean
public CacheManager cacheManager() {
log.debug("Starting Ehcache");
cacheManager = net.sf.ehcache.CacheManager.create();
cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
log.debug("Registering Ehcache Metrics gauges");
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
String name = entity.getName();
if (name == null || entity.getJavaType() != null) {
name = entity.getJavaType().getName();
}
Assert.notNull(name, "entity cannot exist without a identifier");
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L));
net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
}
}
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}
@Override
public List<Movie> findRange(String field, String searchTerm, int firstResult, int maxResults) {
CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Movie> cq = qb.createQuery(Movie.class);
Root<Movie> root = cq.from(Movie.class);
EntityType<Movie> type = entityManager.getMetamodel().entity(Movie.class);
Path<String> path = root.get(type.getDeclaredSingularAttribute(field, String.class));
Predicate condition = qb.like(path, "%" + searchTerm + "%");
cq.where(condition);
TypedQuery<Movie> q = entityManager.createQuery(cq);
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
return q.getResultList();
}
@SuppressWarnings("unchecked")
public <T> Predicate byPattern(Root<T> root, CriteriaBuilder builder, SearchParameters sp, Class<T> type) {
if (!sp.hasSearchPattern()) {
return null;
}
List<Predicate> predicates = newArrayList();
EntityType<T> entity = em.getMetamodel().entity(type);
String pattern = sp.getSearchPattern();
for (SingularAttribute<? super T, ?> attr : entity.getSingularAttributes()) {
if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) {
continue;
}
if (attr.getJavaType() == String.class) {
predicates.add(jpaUtil.stringPredicate((Expression<String>) root.get(jpaUtil.attribute(entity, attr)), pattern, sp, builder));
}
}
return jpaUtil.orPredicate(builder, predicates);
}
/**
* Verify via {@link EntityManager} if one of the attributes of the selected entity
* contains a embedded attribute.
* Return true if at least one embedded attribute is found or false if non embedded
* attribute is found.
*
* @param em according entity manager
* @param jpqlQuery query to verify
* @return true if at least one embedded attribute is found or false if non embedded
* attribute is found.
*/
private static boolean containsEmbeddedAttributes(EntityManager em, String jpqlQuery) {
Set<EntityType<?>> types = em.getMetamodel().getEntities();
int pos = jpqlQuery.indexOf("FROM ") + 5;
int lastpos = jpqlQuery.indexOf(" ", pos);
final String queriedEntity = jpqlQuery.substring(pos, lastpos);
for (EntityType<?> type : types) {
if(queriedEntity.equals(type.getName())) {
Set<Attribute<?, ?>> attributes = (Set<Attribute<?, ?>>) type.getAttributes();
for (Attribute<?, ?> attribute : attributes) {
if(jpqlQuery.contains(attribute.getName()) &&
attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.EMBEDDED) {
return true;
}
}
}
}
return false;
}
private static EntityManager mockEntityManager() {
EntityManager em = EasyMock.createMock(EntityManager.class);
Metamodel mm = EasyMock.createMock(Metamodel.class);
EasyMock.expect(em.getMetamodel()).andReturn(mm).anyTimes();
Set<EntityType<?>> et = new HashSet<EntityType<?>>();
EasyMock.expect(mm.getEntities()).andReturn(et).anyTimes();
EasyMock.expect(em.isOpen()).andReturn(true).anyTimes();
Query jpqlquery = EasyMock.createMock(Query.class);
Capture<String> capturedArgument = new Capture<String>();
EasyMock.expect(em.createQuery(EasyMock.capture(capturedArgument))).andReturn(jpqlquery).anyTimes();
EasyMock.expect(jpqlquery.setParameter(EasyMock.anyInt(), EasyMock.anyObject()))
.andReturn(jpqlquery).anyTimes();
EasyMock.expect(jpqlquery.setParameter(EasyMock.anyInt(), (Calendar) EasyMock.anyObject(),
EasyMock.anyObject(TemporalType.TIMESTAMP.getClass()))).andReturn(jpqlquery).anyTimes();
EasyMock.expect(jpqlquery.setParameter(EasyMock.anyInt(), (Time) EasyMock.anyObject(),
EasyMock.anyObject(TemporalType.TIME.getClass()))).andReturn(jpqlquery).anyTimes();
List<Object> result = new ArrayList<Object>();
result.add(5);
EasyMock.expect(jpqlquery.getResultList()).andReturn(result).anyTimes();
EasyMock.replay(em, mm, jpqlquery);
return em;
}
private <T> String getTableName(EntityManager em, Class<T> entityClass){
/*
* Check if the specified class is present in the metamodel.
* Throws IllegalArgumentException if not.
*/
Metamodel meta = em.getMetamodel();
EntityType<T> entityType = meta.entity(entityClass);
//Check whether @Table annotation is present on the class.
Table t = entityClass.getAnnotation(Table.class);
String tableName = (t == null) ? entityType.getName().toUpperCase() : t.name();
return tableName;
}
@Test
public void testMetamodel(TestContext context) {
EntityType<GuineaPig> pig = getSessionFactory().getMetamodel().entity(GuineaPig.class);
context.assertNotNull(pig);
context.assertEquals( 3, pig.getAttributes().size() );
context.assertEquals( "GuineaPig", pig.getName() );
}
@Override
public void populateEntityDictionary(EntityDictionary dictionary) {
if (elideProperties.isSpringDependencyInjection()) {
logger.info("Spring Dependency Injection is enabled, "
+ "each time an object of entityClass type is instantiated by Elide, "
+ "Spring will try to inject beans.");
}
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
/* bind all entities */
entities.stream()
.map(EntityType::getJavaType)
.filter(Objects::nonNull)
.forEach(mappedClass -> {
try {
// Ignore this result.
// We are just checking to see if it throws an exception meaning that
// provided class was _not_ an entity.
dictionary.lookupEntityClass(mappedClass);
// Bind if successful
dictionary.bindEntity(mappedClass);
if (elideProperties.isSpringDependencyInjection()) {
// Bind Spring Dependency Injection
dictionary.bindInitializer(beanFactory::autowireBean, mappedClass);
}
} catch (IllegalArgumentException e) {
// Ignore this entity
// Turns out that hibernate may include non-entity types in this list when using things
// like envers. Since they are not entities, we do not want to bind them into the entity
// dictionary
}
});
}
private List<Map<String, ?>> recordsInfo() {
List<Map<String, ?>> records = U.list();
for (EntityType<?> type : JPA.getEntityTypes()) {
Class<?> javaType = type.getJavaType();
long count = JPA.count(javaType);
String idType = type.getIdType() != null ? type.getIdType().getJavaType().getSimpleName() : "";
Object superType = type.getSupertype() != null ? type.getSupertype().getJavaType().getSimpleName() : "";
records.add(U.map("type", type.getName(), "extends", superType, "ID Type", idType, "count", count));
}
return records;
}
public int count(String field, String searchTerm) {
CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
Root<Movie> root = cq.from(Movie.class);
EntityType<Movie> type = entityManager.getMetamodel().entity(Movie.class);
Path<String> path = root.get(type.getDeclaredSingularAttribute(field, String.class));
Predicate condition = qb.like(path, "%" + searchTerm + "%");
cq.select(qb.count(root));
cq.where(condition);
return entityManager.createQuery(cq).getSingleResult().intValue();
}
@Override
public org.apache.olingo.odata2.api.edm.provider.EntityType getEdmEntityType() {
org.apache.olingo.odata2.api.edm.provider.EntityType entityType =
new org.apache.olingo.odata2.api.edm.provider.EntityType();
entityType.setName("SalesOrderHeader");
return entityType;
}
public Root from(Class<T> entityClass) {
EntityType<T> entityType = criteriaBuilder.getEntityManagerFactory()
.getMetamodel()
.entity( entityClass );
if ( entityType == null ) {
throw new IllegalArgumentException( entityClass + " is not an entity" );
}
return from( entityType );
}
public <X> Root<X> from(Class<X> entityClass) {
EntityType<X> entityType = criteriaBuilder.getEntityManagerFactory()
.getMetamodel()
.entity( entityClass );
if ( entityType == null ) {
throw new IllegalArgumentException( entityClass + " is not an entity" );
}
return from( entityType );
}
@SuppressWarnings("unchecked")
public <E> List<E> getAllEntities() {
List<E> all = U.list();
for (EntityType<?> entityType : getEntityTypes()) {
all.addAll((List<E>) of(entityType.getJavaType()).all());
}
return all;
}
public boolean appliesTo(EntityType<? super T> entityType) {
if ( this.entityType.equals( entityType ) ) {
return true;
}
IdentifiableType superType = entityType.getSupertype();
while ( superType != null ) {
if ( superType.equals( entityType ) ) {
return true;
}
superType = superType.getSupertype();
}
return false;
}
@Override
public String getKeyColumn(JSONObject aRecord, RegistryConfiguration registryConf) {
String toReturn = null;
logger.debug("IN");
EntityManager entityManager = null;
try {
Assert.assertNotNull(aRecord, "Input parameter [record] cannot be null");
Assert.assertNotNull(aRecord, "Input parameter [registryConf] cannot be null");
logger.debug("New record: " + aRecord.toString(3));
logger.debug("Target entity: " + registryConf.getEntity());
entityManager = dataSource.getEntityManager();
Assert.assertNotNull(entityManager, "entityManager cannot be null");
EntityType targetEntity = getTargetEntity(registryConf, entityManager);
String keyAttributeName = getKeyAttributeName(targetEntity);
logger.debug("Key attribute name is equal to " + keyAttributeName);
toReturn = keyAttributeName;
} catch (Throwable t) {
logger.error(t);
throw new SpagoBIRuntimeException("Error searching for key column", t);
} finally {
if (entityManager != null) {
if (entityManager.isOpen()) {
entityManager.close();
}
}
}
logger.debug("OUT");
return toReturn;
}
/**
* Gets the attribute names for the primary keys from the given entity type.
*
* @param entityType The entity type of the data object.
* @return A list of primary key attribute names.
*/
protected List<String> getPrimaryKeyAttributeNames(EntityType<?> entityType) {
List<String> primaryKeyAttributeNames = new ArrayList<String>();
// JHK: After examining of the metadata structures of EclipseLink, I determined that there
// was nothing in those which preserved the order of the original annotations.
// We *need* to know the order of PK fields for KNS/KRAD functionality.
// So, I'm falling back to checking the annotations and fields on the referenced objects.
// Yes, the Javadoc states that the getDeclaredFields() method does not guarantee order,
// But, it's the best we have. And, as of Java 6, it is returning them in declaration order.
if (entityType.getIdType() instanceof EmbeddableType) {
for (Field pkField : entityType.getIdType().getJavaType().getDeclaredFields()) {
primaryKeyAttributeNames.add(pkField.getName());
}
} else {
// First, get the ID attributes from the metadata
List<String> unsortedPkFields = new ArrayList<String>();
for (SingularAttribute attr : entityType.getSingularAttributes()) {
if (attr.isId()) {
unsortedPkFields.add(attr.getName());
}
}
getPrimaryKeyNamesInOrder(primaryKeyAttributeNames, unsortedPkFields, entityType.getJavaType().getDeclaredFields(), entityType.getJavaType());
}
return primaryKeyAttributeNames;
}
private static Class<?> idType(Class<?> entityType) {
for (EntityType<?> t : JPA.getEntityTypes()) {
if (t.getJavaType().equals(entityType)) {
return t.getIdType() != null ? t.getIdType().getJavaType() : null;
}
}
return null;
}
private void remove(final Object[] args, final Class<?> returnType) {
if (args != null && args.length == 1 && returnType.equals(Void.TYPE)) {
Object entity = args[0];
if (!em.contains(entity)) { // reattach the entity if possible
final Class<?> entityClass = entity.getClass();
final EntityType<? extends Object> et = em.getMetamodel().entity(entityClass);
if (!et.hasSingleIdAttribute()) {
throw new IllegalArgumentException("Dynamic EJB doesn't manage IdClass yet");
}
SingularAttribute<?, ?> id = null; // = et.getId(entityClass); doesn't work with openJPA
for (final SingularAttribute<?, ?> sa : et.getSingularAttributes()) {
if (sa.isId()) {
id = sa;
break;
}
}
if (id == null) {
throw new IllegalArgumentException("id field not found");
}
final String idName = id.getName();
final Object idValue = getProperty(entity, idName);
entity = em.getReference(et.getJavaType(), idValue);
if (entity == null) {
throw new IllegalArgumentException("entity " + entity + " is not managed and can't be found.");
}
}
em.remove(entity);
} else {
throw new IllegalArgumentException(REMOVE_NAME + " should have only one parameter and return void");
}
}
@Override
public void afterPropertiesSet() throws Exception {
Set<String> names = new HashSet<>();
Set<EntityType<?>> entities = em.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
names.add(entity.getName());
}
String suffixPattern = "/**/*" + suffix;
if (!names.isEmpty()) {
String pattern;
if (StringUtils.isNotBlank(templateBasePackage)) {
pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
ClassUtils.convertClassNameToResourcePath(templateBasePackage) + suffixPattern;
loadPatternResource(names, pattern);
}
if (StringUtils.isNotBlank(templateLocation)) {
pattern = templateLocation.contains(suffix) ? templateLocation : templateLocation + suffixPattern;
try {
loadPatternResource(names, pattern);
} catch (FileNotFoundException e) {
if ("classpath:/sqls".equals(templateLocation)) {
//warn: default value
logger.warn("templateLocation[" + templateLocation + "] not exist!");
logger.warn(e.getMessage());
} else {
//throw: custom value.
throw e;
}
}
}
}
}
@Override
public void discoverElements(MetaProviderContext context) {
if (entityManagerFactory != null) {
Set<EmbeddableType<?>> embeddables = entityManagerFactory.getMetamodel().getEmbeddables();
for (EmbeddableType<?> embeddable : embeddables) {
context.getLookup().getMeta(embeddable.getJavaType(), MetaJpaDataObject.class);
}
Set<EntityType<?>> entities = entityManagerFactory.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
context.getLookup().getMeta(entity.getJavaType(), MetaJpaDataObject.class);
}
}
}