当前位置: 首页 > 面试题库 >

从Spring MVC XML文件移动到javaconfig。我的数据库XML文件真的让我迷茫了

宰父俊彦
2023-03-14
问题内容

我从Spring MVC XML文件移动到javaconfig。我的数据库XML文件真的让我迷茫了。我不知道如何使Hibernate4工作以及我的JBoss
JNDI数据源工作。有人可以告诉我如何使javaconfig类像这种XML一样工作。

这是我的database.xml:

?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jee="http://www.springframework.org/schema/jee"

    xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/context
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd
                            http://www.springframework.org/schema/tx
                            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                            http://www.springframework.org/schema/jdbc
                            http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
                            http://www.springframework.org/schema/jee
                            http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">


    <context:property-placeholder location="classpath:app.properties" />

    <context:component-scan base-package="org.uftwf" />

    <tx:annotation-driven transaction-manager="hibernateTransactionManager" />

    <jee:jndi-lookup id="dataSource" jndi-name="java:jboss/datasources/mySQLDB"
        expected-type="javax.sql.DataSource" />

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>org.uftwf.inquiry.model.MemberInquiryInformation</value>

            </list>
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.use_sql_comments">${hibernate.use_sql_comments}</prop>
                <prop key="format_sql">${format_sql}</prop>
            </props>
        </property>
    </bean>

    <bean id="hibernateTransactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>

这是我的javaconfig类:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages= {"org.uftwf.inquiry"})
@ImportResource("/WEB-INF/spring/root-config.xml")
public class WebMVCConfig extends WebMvcConfigurerAdapter {

    private static final String MESSAGE_SOURCE = "/WEB-INF/classes/messages";

    private static final Logger logger = LoggerFactory.getLogger(WebMVCConfig.class);


    @Value("${jdbc.driverClassName}")
    private String driverClassName;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    @Value("${hibernate.dialect}")
    private String hibernateDialect;

    @Value("${hibernate.show_sql}")
    private String hibernateShowSql;

    @Value("${hibernate.hbm2ddl.auto}")
    private String hibernateHbm2ddlAuto;

    @Bean
    public PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer()
    {
        PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        ppc.setLocation(new ClassPathResource("application.properties"));
        ppc.setIgnoreUnresolvablePlaceholders(true);
        return ppc;
    }

    @Bean()
    public DataSource getDataSource()
    {
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName(driverClassName);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactory()
    {

        LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
        factoryBean.setDataSource(getDataSource());
        factoryBean.setHibernateProperties(getHibernateProperties());
        factoryBean.setPackagesToScan("org.uftwf.inquiry.model");

        return factoryBean;
    }

    @Bean
    public Properties getHibernateProperties()
    {
        Properties hibernateProperties = new Properties();

        hibernateProperties.setProperty("hibernate.dialect",  hibernateDialect);
        //hibernateProperties.setProperty("hibernate.show_sql", "true");
        //hibernateProperties.setProperty("hibernate.format_sql", "true");
        hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "update");
        hibernateProperties.setProperty("javax.persistence.validation.mode", "none");

        //Audit History flags
        hibernateProperties.setProperty("org.hibernate.envers.store_data_at_delete", "true");
        hibernateProperties.setProperty("org.hibernate.envers.global_with_modified_flag", "true");

        return hibernateProperties;
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory sessionFactory)
    {
        HibernateTransactionManager htm = new HibernateTransactionManager();
        htm.setSessionFactory(sessionFactory);
        return htm;
    }

    @Bean
    public  ViewResolver resolver() {
        UrlBasedViewResolver url = new UrlBasedViewResolver();
        url.setPrefix("/WEB-INF/view/");
        url.setViewClass(JstlView.class);
        url.setSuffix(".jsp");
        return url;
    }


    @Bean(name = "messageSource")
    public MessageSource configureMessageSource() {
        logger.debug("setting up message source");
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename(MESSAGE_SOURCE);
        messageSource.setCacheSeconds(5);
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver lr = new SessionLocaleResolver();
        lr.setDefaultLocale(Locale.ENGLISH);
        return lr;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        logger.debug("setting up resource handlers");
        registry.addResourceHandler("/resources/").addResourceLocations("/resources/**");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        logger.debug("configureDefaultServletHandling");
        configurer.enable();
    }

    @Override
    public void addInterceptors(final InterceptorRegistry registry) {
        registry.addInterceptor(new LocaleChangeInterceptor());
    }

    @Bean
    public SimpleMappingExceptionResolver simpleMappingExceptionResolver() {
        SimpleMappingExceptionResolver b = new SimpleMappingExceptionResolver();

        Properties mappings = new Properties();
        mappings.put("org.springframework.web.servlet.PageNotFound", "p404");
        mappings.put("org.springframework.dao.DataAccessException", "dataAccessFailure");
        mappings.put("org.springframework.transaction.TransactionException", "dataAccessFailure");
        b.setExceptionMappings(mappings);
        return b;
    }

    @Bean
    public RequestTrackerConfig requestTrackerConfig()
    {
        RequestTrackerConfig tr = new RequestTrackerConfig();
        tr.setPassword("Waiting#$");
        tr.setUrl("https://uftwfrt01-dev.uftmasterad.org/REST/1.0");
        tr.setUser("root");

        return tr;
    }


}

我认为我缺少的部分如下,但请多检查我的课

<context:property-placeholder location="classpath:app.properties" />

    <context:component-scan base-package="org.uftwf" />

    <tx:annotation-driven transaction-manager="hibernateTransactionManager" />

    <jee:jndi-lookup id="dataSource" jndi-name="java:jboss/datasources/mySQLDB"
        expected-type="javax.sql.DataSource" />

问题答案:

对于

<tx:annotation-driven transaction-manager="hibernateTransactionManager" />

注释你的配置类,WebMVCConfig

@EnableTransactionManagement

对于

<context:component-scan base-package="org.uftwf" />

将Package String添加到您的@ComponentScan字段basePackages

对于

<context:property-placeholder location="classpath:app.properties" />

注释您的Configuration类

@PropertySource(value = "classpath:app.properties")

然后做你的PropertyPlaceholderConfigurer @Bean方法static

对于

 <jee:jndi-lookup id="dataSource" jndi-name="java:jboss/datasources/mySQLDB"
    expected-type="javax.sql.DataSource" />

我想你可以做

@Bean
public DataSource dataSource() throws Exception {
    Context ctx = new InitialContext();
    return (DataSource) ctx.lookup("java:jboss/datasources/mySQLDB");
}

无需自动装配会话工厂,只需调用您的@Bean方法

@Bean
public HibernateTransactionManager transactionManager()
{
    HibernateTransactionManager htm = new HibernateTransactionManager();
    htm.setSessionFactory(sessionFactory());
    return htm;
}


 类似资料:
  • 这是我的pom: 如果您需要更多的信息,让我知道我会修改,但我的TestNG文件实际上只是调用一个测试类,没有任何修饰,如果我直接将它作为TestNG测试执行,它就可以工作。其余的代码可以工作,所以我假设不是这样。也许是Eclipse中的设置?

  • 问题内容: 是否可以将数据从XML文件导入到SQL数据库,如果可以,该怎么做。我有一个包含约50000条目的XML文件,我必须创建一个可以操纵该数据(主要是读取和比较)的应用程序- 因此,我担心的是使用该数量的数据进行操纵(而且很可能未来还会有更多)将会非常缓慢且效率低下。如果您认为还有其他选择会更好,请告知。谢谢 问题答案: 您可以使用SQL Server导入和导出向导。您还可以查看SQL Se

  • 问题内容: 我只是在评估H2数据库…下载并解压缩了安装文件,并连接到的数据库。是我的主目录,不存在(我希望H2创建它)。 控制台似乎可以正常工作。我创建了一个表并向其中插入了一行。即使断开并重新连接控制台,我也可以看到并查询该表。 但是,我没有看到预期的文件。它在哪里? 问题答案: 您确定没有: 文件?如果没有,请尝试以下操作: 它的作用是寻找H2控制台的Java进程,获取其PID并列出该进程的所

  • 我有一个码头工人。编写文件,当我启动它时,我希望它创建一个包含一些表的数据库。 我的码头工人组成: 项目结构: 实际的 SQL 文件: -- 主机:本地主机 数据库:待办事项 --服务器版本8.0.18 /*!40101 SET@OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT /; /! 40101 SET@OLD_CHARACTER_SET_RES

  • 本文向大家介绍C#从数据库读取数据到DataSet并保存到xml文件的方法,包括了C#从数据库读取数据到DataSet并保存到xml文件的方法的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了C#从数据库读取数据到DataSet并保存到xml文件的方法。分享给大家供大家参考。具体实现方法如下: DataSet有一个WriteXml方法可以直接将数据保存到xml文件 希望本文所述对大家的C#程

  • 文档:https://eggjs.org/zh-cn/tutorials/sequelize.html sequelize 数据库迁移命令 命令 含义 sequelize db:migrate 运行迁移文件 sequelize db:migrate:status 列出所有迁移的状态 sequelize db:migrate:undo 隔离数据库:迁移:撤消 sequelize db:migrate