java - Hibernate不自动生成表

标签 java spring hibernate spring-mvc

AYY

我正在制作一个简单的 Spring MVC Web 应用程序。我可以很好地运行该应用程序,但如果我尝试登录,我会收到以下信息(我修剪了我认为不相关的所有消息):

INFO: HHH000412: Hibernate Core {5.2.6.Final}
org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
INFO: HCANN000001: Hibernate Commons Annotations{5.0.1.Final}
org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
org.springframework.security.authentication.InternalAuthenticationServiceException: PreparedStatementCallback; bad SQL grammar [SELECT username, password, enabled FROM Users WHERE username=?]; nested exception is java.sql.SQLSyntaxErrorException: Table 'ElsLoggerSchema.Users' doesn't exist

我使用 spring security 来验证用户身份。我希望 Hibernate 自动生成表,我的架构存在,但没有表。这是 Spring Security 的配置:

  @Configuration
    @EnableGlobalMethodSecurity
    @EnableWebSecurity
    @Import({SpringConfiguration.class})
    public class SecurityContext extends WebSecurityConfigurerAdapter {

        @Autowired
        private DataSource dataSource;  

        // authorizeRequests() -> use-expresions = "true"
        @Override
        protected void configure(HttpSecurity http) throws Exception {

            http.authorizeRequests()
                .antMatchers("/createaccount","/error", "/register", "/login", "/newaccount", "/resources/**").permitAll()
                .antMatchers("/**", "/*", "/").authenticated()
                .anyRequest().authenticated()
                    .and()
                .formLogin().loginPage("/login").defaultSuccessUrl("/dashboard").loginProcessingUrl("/j_spring_security_check")
                .usernameParameter("username").passwordParameter("password").failureUrl("/login?error=true")
                    .and()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/login").invalidateHttpSession(true);
        }


        // Equivalent of jdbc-user-service in XML
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{

            auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("SELECT username, password, enabled FROM Users WHERE username=?")
                .authoritiesByUsernameQuery("SELECT username, authority FROM authorities where username=?");
        }

    }

我的 hibnerate 持久化配置就在这里,它包括设置 Hibernate 属性:

    @Configuration
    @EnableTransactionManagement
    @PropertySource({ "/WEB-INF/persistence-mysql.properties" })
    @ComponentScan({ "com.LearnersLogger" })
    @Import({SpringConfiguration.class})
    public class PersistenceConfig {

        @Autowired
        private Environment env;

        @Autowired
        private DataSource dataSource;

        @Bean(name="sessionFactory")
        public LocalSessionFactoryBean sessionFactory() {
            LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
            sessionFactory.setDataSource(dataSource);
            sessionFactory.setPackagesToScan("com.LearnersLogger");
            try {
                sessionFactory.setHibernateProperties(hibernateProperties());
            } catch (Exception e){
                System.out.println("Error with instantiating session factory");
                throw new RuntimeException(e);
            }

            return sessionFactory;
        }


        @Bean
        @Autowired
        public HibernateTransactionManager transactionManager(SessionFactory sessionFactory){

            HibernateTransactionManager htm = new HibernateTransactionManager();
            htm.setSessionFactory(sessionFactory);

            return htm;
        }

        @Bean
        @Autowired
        public HibernateTemplate getHibernateTemplate(SessionFactory sessionFactory){
            HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);
            return hibernateTemplate;
        }

        public Properties hibernateProperties() {

            Properties properties = new Properties();
            properties.put("hibernate.hbm2dll.auto", this.env.getProperty("hibernate.hbm2ddl.auto"));
            properties.put("hibernate.dialect", this.env.getProperty("hibernate.dialect"));
            properties.put("hibernate.show", this.env.getProperty("hibernate.show_sql"));

            return properties;
        }

        @Bean
        public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
            return new PersistenceExceptionTranslationPostProcessor();
        }

    }

我的用户模型如下所示:

@Entity
@Table(name = "Users")
public class User implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 5729727545813781294L;

    public User(){

    }

    // various attributes typical to a User object model
}

我尝试更改 hibernate.hbm2ddl.auto 来更新、创建和创建删除,但没有效果。 我的问题是,我缺少什么或者什么可能导致我的应用程序无法自动生成表的问题?

最佳答案

这里有一个拼写错误, Prop 名称应该是 hibernate.hbm2ddl.auto:

properties.put("hibernate.hbm2dll.auto", this.env.getProperty("hibernate.hbm2ddl.auto"));

关于java - Hibernate不自动生成表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42458303/

相关文章:

java - 来自 Jackson 2.2 的 ObjectMapper 的 pretty-print JSON

java - 从 Parse.com 获取到 Android Spinner 的列表

java - 你能为viewpager2设置OnClickListener吗?

java - 如何使用 JdbcTemplate 查询对象函数传递字符串数组查询字符串?

java - Spring + hibernate : manually commit the transaction at end

java - hibernate native 查询,计数

java - Jackson 序列化忽略使用非 jackson 注释注释的字段

spring - 跨多个 Gradle 项目重用 spring 测试上下文

java - 根据Java,这个方法是线程安全的吗

java - org.springframework.orm.hibernate3.support.BlobByteArrayType 有什么用?