Spring Data配置和Postgres数据库集成(NO xml配置)

时间:2015-11-25 14:55:16

标签: spring postgresql jpa

我有一个基于Spring Framework的项目,它仅基于Java配置进行初始化。这意味着无需使用 web.xml 文件。

您可以在下图中看到项目的结构:

enter image description here

使用的技术:

  • Java 7
  • Spring framework 4.2.1.RELEASE
  • Hibernate ORM 5.0.4.Final
  • Spring Tool Suite IDE 3.6.2
  • Maven 3
  • Tomcat 7

初始化配置文件

" main" class被称为AppInitializer,它位于初始值设定项文件夹

AppInitializer

public class AppInitializer implements WebApplicationInitializer {

    private static final String CONFIG_LOCATION = "com.project.app.config";
    private static final String MAPPING_URL = "/";

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        // Create the 'root' Spring application context
        WebApplicationContext context = getContext();

        // Manage the lifecycle of the root application context
        servletContext.addListener(new ContextLoaderListener(context));

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet",
                new DispatcherServlet(context));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping(MAPPING_URL);

    }

    private AnnotationConfigWebApplicationContext getContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation(CONFIG_LOCATION);

        return context;
    }

}

..而我的配置类位于 config 文件夹

WebMvcConfig

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "com.project.app" })
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private Environment env;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("hello");
    }

    @Bean
    public ApplicationContextProvider applicationContextProvider() {
        return new ApplicationContextProvider();
    }
}

数据库配置文件

此时我想在我的项目中添加一个 postgres 数据库,因此我在CONFIG_LOCATION中创建了一个名为 db 的文件夹,这样春天就会#34 ;拿起" @Configuration类。(使用PGAdmin创建新数据库之后)..我创建了以下配置类。

数据源

@Component
@PropertySource("classpath:application.properties")
public class DataSources {

    @Autowired
    private Environment env;

    @Bean
    @Primary
    public DataSource dataSource() {
        org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();

        String url = env.getProperty(SystemSettings.DS_URL);
        String user = env.getProperty(SystemSettings.DS_USERNAME);
        String pass = env.getProperty(SystemSettings.DS_PASSWORD);

        ds.setDriverClassName("org.postgresql.Driver");
        ds.setUrl(url);
        ds.setUsername(user);
        ds.setPassword(pass);

        return ds;
    }

}

SystemSettings 包含数据库的用户名,密码和网址

@Service
@Configuration
public class SystemSettings implements Settings {  

    public static final String DS_URL = "datasource.app.url";
    public static final String DS_USERNAME = "datasource.app.username";
    public static final String DS_PASSWORD = "datasource.app.password";

    @Autowired
    private Environment env;

    @Override
    public String get(String key) {
        return env.getProperty(key);
    }

}

这些值从 application.properties 文件中获取,如 DataSources 类中所示。

  

spring.jpa.database = POSTGRESQL
  spring.jpa.show-SQL =真
  spring.jpa.hibernate.ddl-AUTO =更新
  datasource.app.type = POSTGRESQL
  datasource.app.url = JDBC:在PostgreSQL://本地主机:5432 /应用
  datasource.app.username = user datasource.app.password = pass

实体和存储库

我继续添加一个实体类,它将代表项目中的一个简单表。 它位于 services / entities 文件夹

StopJPA

@Entity
@Table(name = "stop")
public class StopJPA {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @Column(name = "description")
    private String stopDescription;

    @Column(name = "idStop")
    private String idStop;

    public StopJPA() {
    }

    public StopJPA(String stopDescription, String idStop) {
        this.stopDescription = stopDescription;
        this.idStop = idStop;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getStopDescription() {
        return stopDescription;
    }

    public void setStopDescription(String stopDescription) {
        this.stopDescription = stopDescription;
    }

    public String getIdStop() {
        return idStop;
    }

    public void setIdStop(String idStop) {
        this.idStop = idStop;
    }

}

然后我为这个表创建了一个扩展 CrudRepository 的存储库接口。

StopRepository

/**
 * Repository interface for StopJPA entities.
 */
@Repository
@RepositoryRestResource(collectionResourceRel = "stop", path = "stop")
public interface StopRepository extends CrudRepository<StopJPA, Long> {

    StopJPA findById(@Param("id") Long id);

}

问题

在完成所有这些设置和配置之后,我设法让项目运行但是没有在数据库中创建表。

  • 配置步骤中缺少什么?
  • 我如何让Spring扫描JPA实体并创建数据库?

我的 MAIN INTENTION 是配置Spring(通过使用 Spring Data JPA )和Hibernate,以使它们在不使用的情况下协同工作xml配置文件,没有Spring BOOT依赖项。后者意味着必须手动配置环境&#34;。

更新

我在 DataSources 类中添加了一些配置,并在

中重命名了

PersistenceContext

@Component
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class PersistenceContext {

    @Autowired
    private Environment env;

    @Bean
    @Primary
    public DataSource dataSource() throws ClassNotFoundException {
        org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();

        String url = env.getProperty(SystemSettings.DS_URL);
        String user = env.getProperty(SystemSettings.USERNAME);
        String pass = env.getProperty(SystemSettings.DS_PASSWORD);

        ds.setDriverClassName("org.postgresql.Driver");
        ds.setUrl(url);
        ds.setUsername(user);
        ds.setPassword(pass);

        return ds;
    }

    @Bean
    LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource);
        entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManagerFactoryBean.setPackagesToScan("com.project.app.services.entities");

        Properties jpaProperties = new Properties();

        // Configures the used database dialect. This allows Hibernate to create SQL
        // that is optimized for the used database.
        jpaProperties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));

        // Specifies the action that is invoked to the database when the Hibernate
        // SessionFactory is created or closed.
        jpaProperties.put("hibernate.hbm2ddl.auto",
                env.getRequiredProperty("hibernate.hbm2ddl.auto"));  

        // If the value of this property is true, Hibernate writes all SQL
        // statements to the console.
        jpaProperties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));

        // If the value of this property is true, Hibernate will format the SQL
        // that is written to the console.
        jpaProperties.put("hibernate.format_sql", env.getRequiredProperty("hibernate.format_sql"));

        entityManagerFactoryBean.setJpaProperties(jpaProperties);

        return entityManagerFactoryBean;
    }

    /**
     * Because we are using JPA, we have to create a transaction manager bean that integrates the
     * JPA provider with the Spring transaction mechanism. We can do this by using the
     * JpaTransactionManager class as the transaction manager of our application.
     *
     * We can configure the transaction manager bean by following these steps:
     *
     * -> Create a new JpaTransactionManager object. -> Configure the entity manager factory whose
     * transactions are managed by the created JpaTransactionManager object.
     **/
    @Bean
    JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);
        return transactionManager;
    }
}

Ans还更新了属性文件

  

hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
  hibernate.hbm2ddl.auto = create-drop hibernate.show_sql = false
  hibernate.format_sql = true

     

datasource.app.type = POSTGRESQL
  datasource.app.driverClassName = org.postgresql.Driver
  datasource.app.url = JDBC:在PostgreSQL://本地主机:5432 /应用
  datasource.app.username = user datasource.app.password = pass

不幸的是现在我收到了这个错误

  

严重:无法创建池的初始连接。   java.sql.SQLException:org.postgresql.Driver at   ...... 引起: java.lang.ClassNotFoundException:   org.postgresql.Driver at ......

我不知道为什么它给了我这个例外。 maven依赖是存在的,驱动程序也在类路径中。 。有帮助吗?

2 个答案:

答案 0 :(得分:1)

JPA未指定DDL生成/迁移。默认情况下,Hibernate不执行DDL生成/迁移,但如果configure your persistence.xml properly,则可以执行此操作。

答案 1 :(得分:0)

嗯,这完全是关于Classpath ..我已经在我的 pom.xml 中有了依赖,但我需要做的是

  1. 范围添加为提供,然后
  2. 在Tomcat的库下添加jar (.. {tomcat7_home_path} / lib / postgres jar )。
  3. <强>聚甲醛

            <!-- Postgres -->
            <dependency>
                <groupId>org.postgresql</groupId>
                <artifactId>postgresql</artifactId>
                <version>9.4-1205-jdbc42</version>
                <scope>provided</scope>
            </dependency>
    

    Why must the JDBC driver be put in TOMCAT_HOME/lib folder?