将Annotations转换成sql

自己发现凡是以Hibernate Annotations设定对映关系实体类,可以根据以下的类自动生成sql语句,这样不用在设计表的格式,以下方法自己暂时还看不透,先留着以后琢磨!
package com.bjkyhc.hxast.test;

import static org.junit.Assert.fail;

import java.io.IOException;

import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.MappedSuperclass;

import org.hibernate.MappingException;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.ImprovedNamingStrategy;
import org.hibernate.dialect.Oracle10gDialect;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.ClassUtils;

public class ConfigurationTest {

    private AnnotationConfiguration config = null;
    private static final String RESOURCE_PATTERN = "**/*.class";
    private TypeFilter[] entityTypeFilters = new TypeFilter[] {
            new AnnotationTypeFilter(Entity.class, false),
            new AnnotationTypeFilter(Embeddable.class, false),
            new AnnotationTypeFilter(MappedSuperclass.class, false)};

    private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

    private String[] packagesToScan = {"com.bjkyhc.hxast.models.ecp"};//实体类路径譬如com.bjkyhc.hxast.models.ecp是将ecp下面的实体类转换成sql,注:实体类必须是以Hibernate Annotations设定对映关系
    
    @Before
    public void setUp() throws Exception {
        config = new AnnotationConfiguration();
        config.setNamingStrategy(ImprovedNamingStrategy.INSTANCE);
        
        scanPackages(config);
        
        String[] sqls = config.generateSchemaCreationScript(new Oracle10gDialect());
        String[] dropSqls = config.generateDropSchemaScript(new Oracle10gDialect());
        
        for(String sql:sqls){
            System.out.println(sql+";");//生成Create SQL语句
        }
        
        System.out.println("\n-----#############---drop tables ###############\n");
        
        for(String dropSql:dropSqls){
            System.out.println(dropSql+";");
        }
        
        System.out.println("\n-----#############---end  ###############\n");
        
    }

    @Test
    public void testGenerateDropSchemaScript() {
        
        
    }

    @Test
    public void testGenerateSchemaCreationScript() {
        fail("Not yet implemented");
    }

    @Test
    public void testGenerateSchemaUpdateScript() {
        fail("Not yet implemented");
    }

    @Test
    public void testValidateSchema() {
        fail("Not yet implemented");
    }
    
    /**
     * Perform Spring-based scanning for entity classes.
     * @see #setPackagesToScan
     */
    protected void scanPackages(AnnotationConfiguration config) {
        if (this.packagesToScan != null) {
            try {
                for (String pkg : this.packagesToScan) {
                    String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                            ClassUtils.convertClassNameToResourcePath(pkg) + RESOURCE_PATTERN;
                    Resource[] resources = this.resourcePatternResolver.getResources(pattern);
                    MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
                    for (Resource resource : resources) {
                        if (resource.isReadable()) {
                            MetadataReader reader = readerFactory.getMetadataReader(resource);
                            String className = reader.getClassMetadata().getClassName();
                            if (matchesFilter(reader, readerFactory)) {
                                config.addAnnotatedClass(this.resourcePatternResolver.getClassLoader().loadClass(className));
                            }
                        }
                    }
                }
            }
            catch (IOException ex) {
                throw new MappingException("Failed to scan classpath for unlisted classes", ex);
            }
            catch (ClassNotFoundException ex) {
                throw new MappingException("Failed to load annotated classes from classpath", ex);
            }
        }
    }

    /**
     * Check whether any of the configured entity type filters matches
     * the current class descriptor contained in the metadata reader.
     */
    private boolean matchesFilter(MetadataReader reader, MetadataReaderFactory readerFactory) throws IOException {
        if (this.entityTypeFilters != null) {
            for (TypeFilter filter : this.entityTypeFilters) {
                if (filter.match(reader, readerFactory)) {
                    return true;
                }
            }
        }
        return false;
    }


}


 

你可能感兴趣的:(java)