本文整理汇总了Java中javax.persistence.metamodel.Metamodel.entity方法的典型用法代码示例。如果您正苦于以下问题:Java Metamodel.entity方法的具体用法?Java Metamodel.entity怎么用?Java Metamodel.entity使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.persistence.metamodel.Metamodel
的用法示例。
在下文中一共展示了Metamodel.entity方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getTableName
import javax.persistence.metamodel.Metamodel; //导入方法依赖的package包/类
/**
* Returns the table name for a given entity type in the
* {@link EntityManager}.
*
* @param entityClass
* @return
*/
public <T> String getTableName(Class<T> entityClass) {
/*
* Check if the specified class is present in the metamodel. Throws
* IllegalArgumentException if not.
*/
Metamodel meta = entityManager.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();
logger.debug("Table name found: {}", tableName);
return tableName;
}
示例2: makeSureEntityIDCanbeDetect
import javax.persistence.metamodel.Metamodel; //导入方法依赖的package包/类
@Test
public void makeSureEntityIDCanbeDetect() {
Metamodel model = entityManager.getMetamodel();
final Reflections reflections = new Reflections(EntityIDTest.class.getPackage().getName());
Set<Class<?>> entities = reflections.getTypesAnnotatedWith(Entity.class);
for (Class<?> entity : entities) {
EntityType<?> entityType = model.entity(entity);
Class<?> id = entityType.getIdType().getJavaType();
System.out.println(entityType);
if (entity.equals(InvalidEntity.class)) {
Assert.assertEquals(id, Serializable.class);
} else {
Assert.assertNotEquals(id, Serializable.class);
}
}
}
示例3: printPersistenceModel
import javax.persistence.metamodel.Metamodel; //导入方法依赖的package包/类
public void printPersistenceModel() {
Metamodel metaModel = entityManager.getMetamodel();
Set<EntityType<? extends Object>> types = metaModel.getEntities();
for(EntityType<? extends Object> type : types) {
logger.log(Level.INFO, "--> Type: {0}", type);
Set attributes = type.getAttributes();
for(Object obj : attributes) {
logger.log(Level.INFO, "Name: {0}", ((Attribute)obj).getName());
logger.log(Level.INFO, "isCollection: {0}", ((Attribute)obj).isCollection());
logger.log(Level.INFO, "Name: {0}", ((Attribute)obj).isAssociation());
logger.log(Level.INFO, "Name: {0}", ((Attribute)obj).getPersistentAttributeType());
}
}
EntityType<Item> item = metaModel.entity(Item.class);
}
示例4: getIdProperty
import javax.persistence.metamodel.Metamodel; //导入方法依赖的package包/类
@SuppressWarnings({"unchecked", "rawtypes"})
private String getIdProperty(Class<?> entityClass) {
String idProperty = null;
Metamodel metamodel = this.emf.getMetamodel();
EntityType entity = metamodel.entity( entityClass );
Set<SingularAttribute> singularAttributes = entity.getSingularAttributes();
for ( SingularAttribute singularAttribute : singularAttributes ) {
if ( singularAttribute.isId() ) {
idProperty = singularAttribute.getName();
break;
}
}
if ( idProperty == null ) {
throw new SearchException( "id field not found for: " + entityClass );
}
return idProperty;
}
示例5: filtrados
import javax.persistence.metamodel.Metamodel; //导入方法依赖的package包/类
public List<Produto> filtrados(ProdutoFilter filter) {
Metamodel meta = manager.getMetamodel();
EntityType<Produto> type = meta.entity(Produto.class);
CriteriaBuilder criteriaBuilder = manager.getCriteriaBuilder();
CriteriaQuery<Produto> criteriaQuery = criteriaBuilder.createQuery(Produto.class);
Root<Produto> root = criteriaQuery.from(Produto.class);
if (StringUtils.isNotBlank(filter.getSku())) {
Predicate equalsPredicate = criteriaBuilder.equal(root.get("sku"), filter.getSku());
criteriaQuery.where(equalsPredicate);
}
// vamos usar o atributo nome para filtragem e ordenação
Path<String> nomeAttr = root.get(type.getDeclaredSingularAttribute("nome", String.class));
if (StringUtils.isNotBlank(filter.getNome())) {
Expression<String> expr = criteriaBuilder.lower(nomeAttr);
// where nome like '%nome%'
String match = String.format("%%%s%%", filter.getNome().toLowerCase());
Predicate likePredicate = criteriaBuilder.like(expr, match);
criteriaQuery.where(likePredicate);
}
Order ordernacao = criteriaBuilder.asc(nomeAttr);
criteriaQuery.orderBy(ordernacao);
return manager.createQuery(criteriaQuery).getResultList();
}
示例6: primaryKeyName
import javax.persistence.metamodel.Metamodel; //导入方法依赖的package包/类
/**
* returns the name of the primary key field
*
* @param clazz
* @return
*/
public static <T> String primaryKeyName(Class<T> clazz) {
Metamodel metaModel = Context.internalRequestScope().getApplicationEntityManager().getMetamodel();
EntityType<T> entityType = metaModel.entity(clazz);
if (!entityType.hasSingleIdAttribute()) {
String msg = "Composite persistence ID classes are not supported";
throw new RuntimeException(msg);
}
Class<?> idClass = entityType.getIdType().getJavaType();
log.debug("idClass: " + idClass.getName());
String idName = entityType.getId(idClass).getName();
log.debug("found id for class " + clazz.getName() + ": " + idName);
return idName;
}
示例7: analyze
import javax.persistence.metamodel.Metamodel; //导入方法依赖的package包/类
private void analyze(T aObject)
{
if (aObject != null) {
entityClass = HibernateProxyHelper.getClassWithoutInitializingProxy(aObject);
String idProperty = null;
Metamodel metamodel = getEntityManager().getMetamodel();
EntityType entity = metamodel.entity(entityClass);
Set<SingularAttribute> singularAttributes = entity.getSingularAttributes();
for (SingularAttribute singularAttribute : singularAttributes) {
if (singularAttribute.isId()) {
idProperty = singularAttribute.getName();
break;
}
}
if (idProperty == null) {
throw new RuntimeException("id field not found");
}
DirectFieldAccessor accessor = new DirectFieldAccessor(aObject);
id = (Number) accessor.getPropertyValue(idProperty);
}
else {
entityClass = null;
id = null;
}
}
示例8: doMD
import javax.persistence.metamodel.Metamodel; //导入方法依赖的package包/类
public void doMD(){
Metamodel md = em.getMetamodel();
EntityType<Employee> employee = md.entity(Employee.class);
for(Attribute<? super Employee, ?> attr : employee.getAttributes()){
System.out.println(attr.getName() + " | " + attr.getJavaType().getName() + " | " + attr.getPersistentAttributeType());
}
}
示例9: TwinColumnSearchableSelect
import javax.persistence.metamodel.Metamodel; //导入方法依赖的package包/类
public TwinColumnSearchableSelect(final String fieldName, final SingularAttribute<C, ?> listField,
final SingularAttribute<C, Long> beanIdField, String itemLabel, final boolean isAscending)
{
this.setCaption(fieldName);
mainLayout = new HorizontalLayout();
this.isAscending = isAscending;
this.listField = listField;
beans = new BeanContainer<>(listField.getDeclaringType().getJavaType());
if (beanIdField == null)
{
Metamodel metaModel = EntityManagerProvider.getEntityManager().getMetamodel();
EntityType<C> type = metaModel.entity(listField.getDeclaringType().getJavaType());
this.beanIdField = type.getDeclaredId(Long.class);
}
else
{
this.beanIdField = beanIdField;
}
availableContainer = JpaBaseDao.getGenericDao(listField.getDeclaringType().getJavaType())
.createVaadinContainer();
availableContainer.sort(new Object[]
{ listField.getName() }, new boolean[]
{ isAscending });
if (itemLabel == null)
{
itemLabel = listField.getName();
}
this.itemLabel = itemLabel;
selectedTable = new Table();
selectedTable.setContainerDataSource(createBeanContainer());
if (!selectedTable.getContainerPropertyIds().contains(itemLabel))
{
logger.error("you need to define a getter for the field {} in {}, valid fields are {}", itemLabel,
listField.getDeclaringType().getJavaType(),
Arrays.toString(selectedTable.getContainerPropertyIds().toArray()));
}
selectedTable.addItemClickListener(new ItemClickListener()
{
private static final long serialVersionUID = 1L;
@Override
public void itemClick(ItemClickEvent event)
{
if (event.isDoubleClick())
{
removeButton.click();
}
}
});
selectedTable.setVisibleColumns(itemLabel);
selectedTable.setColumnHeaders("Selected");
selectedTable.setWidth(200, Unit.PIXELS);
selectedTable.setHeight(300, Unit.PIXELS);
selectedTable.setSelectable(true);
selectedTable.setMultiSelect(true);
// setting value of header here so that subclasses can
// modify header if needed
setAvailableColumnHeader(assignAvailableHeaderValue());
createAvailableTable();
addSelectedColumnTooltip();
addNewButton.setVisible(false);
refreshSelected();
}
示例10: createSelectedContainer
import javax.persistence.metamodel.Metamodel; //导入方法依赖的package包/类
private BeanContainer<Long, C> createSelectedContainer()
{
final Metamodel metaModel = EntityManagerProvider.getEntityManager().getMetamodel();
final EntityType<C> type = metaModel.entity(itemClass);
beanIdField = type.getDeclaredId(Long.class);
selectedBeans = new BeanContainer<>(itemClass);
selectedBeans.setBeanIdProperty(beanIdField.getName());
sortSelectedBeans();
return selectedBeans;
}
示例11: findByProperties
import javax.persistence.metamodel.Metamodel; //导入方法依赖的package包/类
@Override
public List<? extends ICommand> findByProperties(Class<? extends ICommand> obj, Map<String, Object> propertiesMap,
List<PropertyOrder> orders, Integer maxResults) {
orders = new ArrayList<PropertyOrder>();
// TODO
// PropertyOrder ord = new PropertyOrder("name", OrderType.ASC);
// orders.add(ord);
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<CommandImpl> criteria = (CriteriaQuery<CommandImpl>) builder.createQuery(CommandImpl.class);
Metamodel metamodel = entityManager.getMetamodel();
EntityType<CommandImpl> entityType = metamodel.entity(CommandImpl.class);
Root<CommandImpl> from = (Root<CommandImpl>) criteria.from(entityType);
criteria.select(from);
Predicate predicate = null;
if (propertiesMap != null) {
Predicate pred = null;
for (Entry<String, Object> entry : propertiesMap.entrySet()) {
if (entry.getValue() != null && !entry.getValue().toString().isEmpty()) {
String[] key = entry.getKey().split("\\.");
if (key.length > 1) {
Join<Object, Object> join = null;
for (int i = 0; i < key.length - 1; i++) {
join = join != null ? join.join(key[i]) : from.join(key[i]);
from.fetch(key[i]);
}
pred = builder.equal(join.get(key[key.length - 1]), entry.getValue());
} else {
pred = builder.equal(from.get(entry.getKey()), entry.getValue());
}
predicate = predicate == null ? pred : builder.and(predicate, pred);
}
}
if (predicate != null) {
criteria.where(predicate);
}
}
if (orders != null && !orders.isEmpty()) {
List<Order> orderList = new ArrayList<Order>();
for (PropertyOrder order : orders) {
orderList.add(order.getOrderType() == OrderType.ASC ? builder.asc(from.get(order.getPropertyName()))
: builder.desc(from.get(order.getPropertyName())));
}
criteria.orderBy(orderList);
}
List<CommandImpl> list = null;
if (null != maxResults) {
list = entityManager.createQuery(criteria).setMaxResults(maxResults).getResultList();
} else {
list = entityManager.createQuery(criteria).getResultList();
}
return list;
}
示例12: findByProperties
import javax.persistence.metamodel.Metamodel; //导入方法依赖的package包/类
private List<?> findByProperties(Class cls, Map<String, Object> propertiesMap, List<PropertyOrder> orders,
Integer maxResults) {
orders = new ArrayList<PropertyOrder>();
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery criteria = builder.createQuery(cls);
Metamodel metamodel = entityManager.getMetamodel();
EntityType entityType = metamodel.entity(cls);
Root from = (Root) criteria.from(entityType);
criteria.select(from);
Predicate predicate = null;
if (propertiesMap != null) {
Predicate pred = null;
for (Entry<String, Object> entry : propertiesMap.entrySet()) {
if (entry.getValue() != null && !entry.getValue().toString().isEmpty()) {
String[] key = entry.getKey().split("\\.");
if (key.length > 1) {
Join<Object, Object> join = null;
for (int i = 0; i < key.length - 1; i++) {
join = join != null ? join.join(key[i]) : from.join(key[i]);
}
pred = builder.equal(join.get(key[key.length - 1]), entry.getValue());
} else {
pred = builder.equal(from.get(entry.getKey()), entry.getValue());
}
predicate = predicate == null ? pred : builder.and(predicate, pred);
}
}
if (predicate != null) {
criteria.where(predicate);
}
}
if (orders != null && !orders.isEmpty()) {
List<Order> orderList = new ArrayList<Order>();
for (PropertyOrder order : orders) {
orderList.add(order.getOrderType() == OrderType.ASC ? builder.asc(from.get(order.getPropertyName()))
: builder.desc(from.get(order.getPropertyName())));
}
criteria.orderBy(orderList);
}
TypedQuery query = entityManager.createQuery(criteria);
if (maxResults != null) {
query.setMaxResults(maxResults.intValue());
}
List list = query.getResultList();
logger.debug("{} objects found: {}", new Object[] { cls.getSimpleName(), list });
return list;
}
示例13: findByProperties
import javax.persistence.metamodel.Metamodel; //导入方法依赖的package包/类
@Override
public List<? extends IPolicy> findByProperties(Class<? extends IPolicy> obj, Map<String, Object> propertiesMap,
List<PropertyOrder> orders, Integer maxResults) {
orders = new ArrayList<PropertyOrder>();
// TODO
// PropertyOrder ord = new PropertyOrder("name", OrderType.ASC);
// orders.add(ord);
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<PolicyImpl> criteria = (CriteriaQuery<PolicyImpl>) builder.createQuery(PolicyImpl.class);
Metamodel metamodel = entityManager.getMetamodel();
EntityType<PolicyImpl> entityType = metamodel.entity(PolicyImpl.class);
Root<PolicyImpl> from = (Root<PolicyImpl>) criteria.from(entityType);
criteria.select(from);
Predicate predicate = null;
if (propertiesMap != null) {
Predicate pred = null;
for (Entry<String, Object> entry : propertiesMap.entrySet()) {
if (entry.getValue() != null && !entry.getValue().toString().isEmpty()) {
String[] key = entry.getKey().split("\\.");
if (key.length > 1) {
Join<Object, Object> join = null;
for (int i = 0; i < key.length - 1; i++) {
join = join != null ? join.join(key[i]) : from.join(key[i]);
}
pred = builder.equal(join.get(key[key.length - 1]), entry.getValue());
} else {
pred = builder.equal(from.get(entry.getKey()), entry.getValue());
}
predicate = predicate == null ? pred : builder.and(predicate, pred);
}
}
if (predicate != null) {
criteria.where(predicate);
}
}
if (orders != null && !orders.isEmpty()) {
List<Order> orderList = new ArrayList<Order>();
for (PropertyOrder order : orders) {
orderList.add(order.getOrderType() == OrderType.ASC ? builder.asc(from.get(order.getPropertyName()))
: builder.desc(from.get(order.getPropertyName())));
}
criteria.orderBy(orderList);
}
List<PolicyImpl> list = null;
if (null != maxResults) {
list = entityManager.createQuery(criteria).setMaxResults(maxResults).getResultList();
} else {
list = entityManager.createQuery(criteria).getResultList();
}
return list;
}
示例14: getEntityMetaModel
import javax.persistence.metamodel.Metamodel; //导入方法依赖的package包/类
private EntityType<T> getEntityMetaModel() {
Metamodel metamodel = getEntityManager().getMetamodel();
EntityType<T> entity = metamodel.entity(domainClass);
return entity;
}
示例15: addPersonTest
import javax.persistence.metamodel.Metamodel; //导入方法依赖的package包/类
@Test
public void addPersonTest() {
System.out.println("--> TEST: addPerson");
// count people before starting
List<Person> list = em.createNamedQuery("Person.findAll", Person.class)
.getResultList();
int originalCount = list.size();
// Arrange
Person at = new Person();
at.setName("Pinci");
at.setLastname("Palleto");
Calendar cal = Calendar.getInstance();
cal.set(1979, Calendar.DECEMBER, 12);
at.setBirthdate(cal.getTime());
System.out.println("--> TEST: addPerson => persisting the new person");
// Act
tx.begin();
em.persist(at);
tx.commit();
// Assert
assertNotNull("Id should not be null", at.getIdPerson());
// Query using CriteriaBuilder and CriteriaQuery Example
int idNewPerson = at.getIdPerson();
System.out.println("--> TEST: addPerson => querying for the new person");
// 1. Prepare the criteria builder and the criteria query to work with the model you want
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Person> cq = cb.createQuery(Person.class);
// setup a metamodel for the root of the query
Metamodel m = em.getMetamodel();
EntityType<Person> Person_ = m.entity(Person.class);
Root<Person> person = cq.from(Person_);
// prepare a parameter expression to setup parameters for the query
ParameterExpression<Integer> p = cb.parameter(Integer.class);
// prepare the query
cq.select(person).where(cb.equal(person.get("idPerson"), p));
// execute the query and set the parameters with values
TypedQuery<Person> tq = em.createQuery(cq);
tq.setParameter(p, idNewPerson);
// get the results
List<Person> newPersonList = tq.getResultList();
assertEquals("Table has one entities", 1, newPersonList.size());
assertEquals("Table has correct name", "Pinci", newPersonList.get(0).getName());
System.out.println("--> TEST: addPerson => deleting the new person");
em.getTransaction().begin();
em.remove(newPersonList.get(0));
em.getTransaction().commit();
list = em.createNamedQuery("Person.findAll", Person.class)
.getResultList();
assertEquals("Table has no entity", originalCount, list.size());
}