优化开发环境下Hibernate的启动效率

Hibernate启动时需要做很多事情,如果实体类不是很多还好,如果很多,我们项目中目前大概有500左右,那么启动速度会很慢,如何加快hibernate的启动速度,网上有很多文章已经阐述了部分,不再重复,补充一些:

 

一.避免使用@NamedQuery,hibernate在启动时会执行namedQuery的绑定/校验等工作,实在避免不了,那么考虑将校验关闭(hibernate.query.startup_check=false)

 

二.将hibernate.hbm2ddl.auto设置为none,如果实在要进行update的工作,可以按模块进行update,如在packages.txt中指定POJO的包名,然后根据包名update涉及的表,下面的代码供参考:

 

    protected void updateDatabaseSchema() {
        try {
            //从packages.txt中读取包名列表
            List<String> packages = null;
            Resource resource = resourceLoader.getResource("classpath:packages.txt");
            if (resource.exists()) {
                packages = new ArrayList<String>();
                List<String> lines = FileUtils.readLines(resource.getFile(), "UTF-8");
                if (lines != null) {
                    for (String line : lines) {
                        if (StringUtils.isNotEmpty(line.trim()) && !packages.contains(line.trim()))
                            packages.add(line.trim());
                    }
                }
            }
            //设置configuration的tables字段
            Field tablesField = ReflectionUtils.findField(Configuration.class, "tables");
            ReflectionUtils.makeAccessible(tablesField);
            Configuration configuration = localSessionFactoryBean.getConfiguration();
            Map tables = (Map) ReflectionUtils.getField(tablesField, configuration);
            try {
                Map tempTables = new HashMap();
                Iterator it = configuration.getClassMappings();
                while (it.hasNext()) {
                    PersistentClass model = (PersistentClass) it.next();
                    if (model.getMappedClass() != null && model.getTable() != null) {
                        String packageName = ClassUtils.getPackageName(model.getMappedClass());
                        if (packages == null || contains(packages, packageName)) {
                            tempTables.put(model.getTable().getName(), model.getTable());
                        }
                    }
                }
                ReflectionUtils.setField(tablesField, localSessionFactoryBean.getConfiguration(), tempTables);
                new SchemaUpdate(configuration, ((SessionFactoryImplementor) localSessionFactoryBean.getObject()).getSettings()).execute(false, true);
            } finally {
                ReflectionUtils.setField(tablesField, localSessionFactoryBean.getConfiguration(), tables);
            }
        } catch (Exception ex) {
            throw new NestedRuntimeException("Exception", ex);
        }
    }

    protected boolean contains(List<String> packages, String packageName) {
        for (String pkgName : packages) {
            if (StringUtils.contains(packageName, pkgName))
                return true;
        }
        return false;
    }
 

你可能感兴趣的:(Hibernate,工作)