下面列出了怎么用javax.persistence.Entity的API类实例代码及写法,或者点击链接到github查看源代码。
private void generateVOViewSql(StringBuilder sb, Class<?> entityClass) {
if (!entityClass.isAnnotationPresent(Entity.class)) {
throw new IllegalArgumentException(String.format("class[%s] is annotated by @EO but not annotated by @Entity", entityClass.getName()));
}
EO at = entityClass.getAnnotation(EO.class);
if (!at.needView()) {
return;
}
Class EOClazz = at.EOClazz();
List<Field> fs = FieldUtils.getAllFields(entityClass);
sb.append(String.format("\nCREATE VIEW `zstack`.`%s` AS SELECT ", entityClass.getSimpleName()));
List<String> cols = new ArrayList<String>();
for (Field f : fs) {
if (!f.isAnnotationPresent(Column.class) || f.isAnnotationPresent(NoView.class)) {
continue;
}
cols.add(f.getName());
}
sb.append(org.apache.commons.lang.StringUtils.join(cols, ", "));
sb.append(String.format(" FROM `zstack`.`%s` WHERE %s IS NULL;\n", EOClazz.getSimpleName(), at.softDeletedColumn()));
}
public void deleteEntities(Class<?> entity){
if(entity == null || entity.getAnnotation(Entity.class) == null){
throw new IllegalArgumentException("Invalid non-entity class");
}
String name = entity.getSimpleName();
/*
Note: we passed as input a Class<?> instead of a String to
avoid SQL injection. However, being here just test code, it should
not be a problem. But, as a good habit, always be paranoiac about
security, above all when you have code that can delete the whole
database...
*/
Query query = em.createQuery("delete from " + name);
query.executeUpdate();
}
private void deleteEntities(Class<?> entity){
if(entity == null || entity.getAnnotation(Entity.class) == null){
throw new IllegalArgumentException("Invalid non-entity class");
}
String name = entity.getSimpleName();
/*
Note: we passed as input a Class<?> instead of a String to
avoid SQL injection. However, being here just test code, it should
not be a problem. But, as a good habit, always be paranoiac about
security, above all when you have code that can delete the whole
database...
*/
Query query = em.createQuery("delete from " + name);
query.executeUpdate();
}
private void deleteEntities(Class<?> entity){
if(entity == null || entity.getAnnotation(Entity.class) == null){
throw new IllegalArgumentException("Invalid non-entity class");
}
String name = entity.getSimpleName();
/*
Note: we passed as input a Class<?> instead of a String to
avoid SQL injection. However, being here just test code, it should
not be a problem. But, as a good habit, always be paranoiac about
security, above all when you have code that can delete the whole
database...
*/
Query query = em.createQuery("delete from " + name);
query.executeUpdate();
}
private void deleteEntities(Class<?> entity){
if(entity == null || entity.getAnnotation(Entity.class) == null){
throw new IllegalArgumentException("Invalid non-entity class");
}
String name = entity.getSimpleName();
/*
Note: we passed as input a Class<?> instead of a String to
avoid SQL injection. However, being here just test code, it should
not be a problem. But, as a good habit, always be paranoiac about
security, above all when you have code that can delete the whole
database...
*/
Query query = em.createQuery("delete from " + name);
query.executeUpdate();
}
public Optional<MetamodelAttributeTarget> jpaEntityTarget() {
DeclaredType attributeType = (DeclaredType) variableElement.asType();
List<? extends TypeMirror> typeArguments = attributeType.getTypeArguments();
// This is the lazy way of doing this. We consider that any sub interfaces of
// javax.persistence.metamodel.Attribute
// will declare the target type as the last type arguments.
// e.g. MapAttribute<Brand, Long, Product> where Product is the target
// TODO do this cleanly by browsing the class hierarchy
DeclaredType targetType = (DeclaredType) typeArguments.get(typeArguments.size() - 1);
TypeElement targetTypeElement = (TypeElement) targetType.asElement();
if (targetTypeElement.getAnnotation(Entity.class) == null) {
return Optional.empty();
}
return Optional.of(
new MetamodelAttributeTarget(
variableElement.getSimpleName().toString(), targetTypeElement));
}
private Entity getEntity(Element tree, XMLContext.Default defaults) {
if ( tree == null ) {
return defaults.canUseJavaAnnotations() ? getPhysicalAnnotation( Entity.class ) : null;
}
else {
if ( "entity".equals( tree.getName() ) ) {
AnnotationDescriptor entity = new AnnotationDescriptor( Entity.class );
copyStringAttribute( entity, tree, "name", false );
if ( defaults.canUseJavaAnnotations()
&& StringHelper.isEmpty( (String) entity.valueOf( "name" ) ) ) {
Entity javaAnn = getPhysicalAnnotation( Entity.class );
if ( javaAnn != null ) {
entity.setValue( "name", javaAnn.name() );
}
}
return AnnotationFactory.create( entity );
}
else {
return null; //this is not an entity
}
}
}
protected List<String> getClasses(Resource[] resources) {
List<String> classNames = new ArrayList<>();
for (Resource resource : resources) {
if (resource.isReadable()) {
MetadataReader metadataReader;
try {
metadataReader = metadataReaderFactory.getMetadataReader(resource);
} catch (IOException e) {
throw new RuntimeException("Unable to read metadata resource", e);
}
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
if (annotationMetadata.isAnnotated(com.haulmont.chile.core.annotations.MetaClass.class.getName())
|| annotationMetadata.isAnnotated(MappedSuperclass.class.getName())
|| annotationMetadata.isAnnotated(Entity.class.getName())) {
ClassMetadata classMetadata = metadataReader.getClassMetadata();
classNames.add(classMetadata.getClassName());
}
}
}
return classNames;
}
/**
* Creates a new {@link AnnotationBasedPersistentProperty}.
* @param property must not be {@literal null}.
* @param owner must not be {@literal null}.
*/
public MybatisPersistentPropertyImpl(Property property,
PersistentEntity<?, MybatisPersistentProperty> owner,
SimpleTypeHolder simpleTypeHolder) {
super(property, owner, simpleTypeHolder);
this.isAssociation = Lazy.of(() -> ASSOCIATION_ANNOTATIONS.stream()
.anyMatch(this::isAnnotationPresent));
this.usePropertyAccess = detectPropertyAccess();
this.associationTargetType = detectAssociationTargetType();
this.updateable = detectUpdatability();
this.isIdProperty = Lazy.of(
() -> ID_ANNOTATIONS.stream().anyMatch(it -> isAnnotationPresent(it)));
this.isEntity = Lazy.of(getActualType().isAnnotationPresent(Entity.class));
}
@Override
public AnnotatedClassType addClassType(XClass clazz) {
AnnotatedClassType type;
if ( clazz.isAnnotationPresent( Entity.class ) ) {
type = AnnotatedClassType.ENTITY;
}
else if ( clazz.isAnnotationPresent( Embeddable.class ) ) {
type = AnnotatedClassType.EMBEDDABLE;
}
else if ( clazz.isAnnotationPresent( javax.persistence.MappedSuperclass.class ) ) {
type = AnnotatedClassType.EMBEDDABLE_SUPERCLASS;
}
else {
type = AnnotatedClassType.NONE;
}
annotatedClassTypeMap.put( clazz.getName(), type );
return type;
}
@SuppressWarnings("unchecked")
public static synchronized List<String> getEntityTypes(String packages[], Class<?>... entities) {
List<String> entityTypes = Scan.annotated(Entity.class).in(packages).getAll();
for (Class<?> entity : entities) {
String type = entity.getName();
if (!entityTypes.contains(type)) {
entityTypes.add(type);
}
}
if (!entityTypes.isEmpty()) {
Log.info("!Found " + entityTypes.size() + " JPA Entities");
}
return entityTypes;
}
private void collectIndex(Class entity) {
List<Field> fs;
Class superClass = entity.getSuperclass();
if (superClass.isAnnotationPresent(Entity.class) || entity.isAnnotationPresent(EO.class)) {
// parent class or EO class is also an entity, it will take care of its foreign key,
// so we only do our own foreign keys;
fs = FieldUtils.getAnnotatedFieldsOnThisClass(Index.class, entity);
} else {
fs = FieldUtils.getAnnotatedFields(Index.class, entity);
}
List<IndexInfo> keyInfos = indexMap.get(entity);
if (keyInfos == null) {
keyInfos = new ArrayList<IndexInfo>();
indexMap.put(entity, keyInfos);
}
for (Field f : fs) {
keyInfos.add(new IndexInfo(entity, f));
}
}
public void deleteEntities(Class<?> entity){
if(entity == null || entity.getAnnotation(Entity.class) == null){
throw new IllegalArgumentException("Invalid non-entity class");
}
String name = entity.getSimpleName();
/*
Note: we passed as input a Class<?> instead of a String to
avoid SQL injection. However, being here just test code, it should
not be a problem. But, as a good habit, always be paranoiac about
security, above all when you have code that can delete the whole
database...
*/
Query query = em.createQuery("delete from " + name);
query.executeUpdate();
}
private void deleteEntities(Class<?> entity){
if(entity == null || entity.getAnnotation(Entity.class) == null){
throw new IllegalArgumentException("Invalid non-entity class");
}
String name = entity.getSimpleName();
/*
Note: we passed as input a Class<?> instead of a String to
avoid SQL injection. However, being here just test code, it should
not be a problem. But, as a good habit, always be paranoiac about
security, above all when you have code that can delete the whole
database...
*/
Query query = em.createQuery("delete from " + name);
query.executeUpdate();
}
private void deleteEntities(Class<?> entity){
if(entity == null || entity.getAnnotation(Entity.class) == null){
throw new IllegalArgumentException("Invalid non-entity class");
}
String name = entity.getSimpleName();
/*
Note: we passed as input a Class<?> instead of a String to
avoid SQL injection. However, being here just test code, it should
not be a problem. But, as a good habit, always be paranoiac about
security, above all when you have code that can delete the whole
database...
*/
Query query = em.createQuery("delete from " + name);
query.executeUpdate();
}
private void deleteEntities(Class<?> entity){
if(entity == null || entity.getAnnotation(Entity.class) == null){
throw new IllegalArgumentException("Invalid non-entity class");
}
String name = entity.getSimpleName();
/*
Note: we passed as input a Class<?> instead of a String to
avoid SQL injection. However, being here just test code, it should
not be a problem. But, as a good habit, always be paranoiac about
security, above all when you have code that can delete the whole
database...
*/
Query query = em.createQuery("delete from " + name);
query.executeUpdate();
}
@Test
public void testGetEntityClassFromNodeLabelsHavingTheLabelDeclaredByTheTableAnnotationWithoutInheritance() throws Exception {
final String simpleClassName = "EntityClass";
final String nodeLabel = "ENTITY_CLASS";
final JPackage jp = jCodeModel.rootPackage();
final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName);
jClass.annotate(Entity.class);
jClass.annotate(Table.class).param("name", nodeLabel);
buildModel(testFolder.getRoot(), jCodeModel);
compileModel(testFolder.getRoot());
final Class<?> entityClass = loadClass(testFolder.getRoot(), jClass.name());
final Class<?> clazz = EntityUtils.getEntityClassFromNodeLabels(Arrays.asList(nodeLabel), Arrays.asList(entityClass));
assertThat(clazz, equalTo(entityClass));
}
@Test
public void testGetNamesOfIdPropertiesFromASingleClassHavingAFieldAnnotatedWithId() throws Exception {
// GIVEN
final String simpleClassName = "EntityClass";
final String idPropertyName = "key";
final JPackage jp = jCodeModel.rootPackage();
final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName);
jClass.annotate(Entity.class);
jClass.field(JMod.PRIVATE, String.class, idPropertyName).annotate(Id.class);
buildModel(testFolder.getRoot(), jCodeModel);
compileModel(testFolder.getRoot());
final Class<?> entityClass = loadClass(testFolder.getRoot(), jClass.name());
// WHEN
final List<String> namesOfIdProperties = EntityUtils.getNamesOfIdProperties(entityClass);
// THEN
assertThat(namesOfIdProperties.size(), equalTo(1));
assertThat(namesOfIdProperties, hasItem(idPropertyName));
}
@Test
public void testGetNamesOfIdPropertiesFromASingleClassHavingAMethodAnnotatedWithId() throws Exception {
// GIVEN
final String simpleClassName = "EntityClass";
final String idPropertyName = "key";
final JPackage jp = jCodeModel.rootPackage();
final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName);
jClass.annotate(Entity.class);
jClass.method(JMod.PUBLIC, jCodeModel.VOID, "getKey").annotate(Id.class);
buildModel(testFolder.getRoot(), jCodeModel);
compileModel(testFolder.getRoot());
final Class<?> entityClass = loadClass(testFolder.getRoot(), jClass.name());
// WHEN
final List<String> namesOfIdProperties = EntityUtils.getNamesOfIdProperties(entityClass);
// THEN
assertThat(namesOfIdProperties.size(), equalTo(1));
assertThat(namesOfIdProperties, hasItem(idPropertyName));
}
public static String getEntityTable(final JavaClass<?> entity)
{
String table = entity.getName();
if (entity.hasAnnotation(Entity.class))
{
Annotation<?> a = entity.getAnnotation(Entity.class);
if (!Strings.isNullOrEmpty(a.getStringValue("name")))
{
table = a.getStringValue("name");
}
else if (!Strings.isNullOrEmpty(a.getStringValue()))
{
table = a.getStringValue();
}
}
return table;
}
private static String getEntityName(Class<?> entityClass) {
String name = entityClass.getAnnotation(Entity.class).name();
if (name == null || name.isEmpty()) {
name = entityClass.getSimpleName();
}
return name;
}
@Test
public void verifyClassTags_containOnlyRequiredClasses() {
ImmutableList<Class> managedClassed = PersistenceXmlUtility.getManagedClasses();
ImmutableList<Class> unnecessaryClasses =
managedClassed.stream()
.filter(
clazz ->
!clazz.isAnnotationPresent(Entity.class)
&& !AttributeConverter.class.isAssignableFrom(clazz))
.collect(toImmutableList());
ImmutableSet<Class> duplicateClasses =
managedClassed.stream()
.filter(clazz -> Collections.frequency(managedClassed, clazz) > 1)
.collect(toImmutableSet());
expect
.withMessage("Found duplicate <class> tags defined in persistence.xml.")
.that(duplicateClasses)
.isEmpty();
expect
.withMessage(
"Found unnecessary <class> tags defined in persistence.xml. Only entity class and"
+ " implementation of AttributeConverter are required to be added in"
+ " persistence.xml.")
.that(unnecessaryClasses)
.isEmpty();
}
/**
* 获取实体名称,由上面的方法调用
* @param <T>
* @param entityClass 实体类
* @return
*/
protected <T> String getEntityName(Class<T> entityClass){
//默认情况下实体名称为这个类的简单名称,即实体类上的这个标志@Entity
String entityname = entityClass.getSimpleName();
//获取实体类Entity注解上的属性,如Entity(name="xxx")这种情况
Entity entity = entityClass.getAnnotation(Entity.class);
//判断实体类Entity注解上是否设置了name属性
if(entity.name() != null && !"".equals(entity.name())){
//把实体名称修改为它的属性值
entityname = entity.name();
}
return entityname;
}
@Override
public String getEntityName() {
Entity entity = domainType.getAnnotation(Entity.class);
boolean hasName = null != entity && StringUtils.hasText(entity.name());
return hasName ? entity.name() : domainType.getSimpleName();
}
private String entityName(Class<?> entityClass) {
String name = entityClass.getDeclaredAnnotation(Entity.class).name();
if (Strings.isNullOrEmpty(name)) {
return entityClass.getSimpleName();
} else {
return name;
}
}
private static List<Class<?>> scanEnhanceClass() throws Exception {
List<Class<?>> list = new ArrayList<Class<?>>();
try (ScanResult scanResult = new ClassGraph().enableAnnotationInfo().scan()) {
List<ClassInfo> classInfos = scanResult.getClassesWithAnnotation(Entity.class.getName());
for (ClassInfo info : classInfos) {
list.add(Class.forName(info.getName()));
}
return list.stream().sorted(Comparator.comparing(Class::getName)).collect(Collectors.toList());
}
}
public ClassPath getCompileClassPath() {
if (compileClassPath == null) {
URL statelessAnnotationURL = Entity.class.getProtectionDomain().getCodeSource().getLocation();
compileClassPath = ClassPathSupport.createClassPath(new URL[] { FileUtil.getArchiveRoot(statelessAnnotationURL) });
}
return compileClassPath;
}
private MetadataSources mapAnnotatedClasses(ServiceRegistry serviceRegistry) {
MetadataSources sources = new MetadataSources(serviceRegistry);
final Reflections reflections = new Reflections();
for (final Class<?> mappedSuperClass : reflections.getTypesAnnotatedWith(MappedSuperclass.class)) {
sources.addAnnotatedClass(mappedSuperClass);
System.out.println("Mapped = " + mappedSuperClass.getName());
}
for (final Class<?> entityClasses : reflections.getTypesAnnotatedWith(Entity.class)) {
sources.addAnnotatedClass(entityClasses);
System.out.println("Mapped = " + entityClasses.getName());
}
return sources;
}
private Set<String> findEntities(String[] allBasePackages, final URL[] classPath)
{
final Set<String> result = new TreeSet<>();
try (final ScanResult scanResult = new ClassGraph().whitelistPackages(allBasePackages).enableAnnotationInfo().overrideClasspath((Object[]) classPath).scan())
{
result.addAll(extract(scanResult, Entity.class));
result.addAll(extract(scanResult, MappedSuperclass.class));
result.addAll(extract(scanResult, Embeddable.class));
result.addAll(extract(scanResult, Converter.class));
}
return result;
}
/**
* 获取全部的Field,仅仅通过Field获取
*
* @param entityClass
* @param fieldList
* @param level
* @return
*/
private List<EntityField> _getFields(Class<?> entityClass, List<EntityField> fieldList, Integer level) {
if (fieldList == null) {
fieldList = new ArrayList<EntityField>();
}
if (level == null) {
level = 0;
}
if (entityClass.equals(Object.class)) {
return fieldList;
}
Field[] fields = entityClass.getDeclaredFields();
int index = 0;
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
//排除静态字段,解决bug#2
if (!Modifier.isStatic(field.getModifiers())) {
if (level.intValue() != 0) {
//将父类的字段放在前面
fieldList.add(index, new EntityField(field, null));
index++;
} else {
fieldList.add(new EntityField(field, null));
}
}
}
Class<?> superClass = entityClass.getSuperclass();
if (superClass != null
&& !superClass.equals(Object.class)
&& (superClass.isAnnotationPresent(Entity.class)
|| (!Map.class.isAssignableFrom(superClass)
&& !Collection.class.isAssignableFrom(superClass)))) {
return _getFields(entityClass.getSuperclass(), fieldList, ++level);
}
return fieldList;
}