休眠不使用postgresql在Spring启动时自动创建表 [英] Hibernate not creating Table automatically in spring boot using postgresql

查看:126
本文介绍了休眠不使用postgresql在Spring启动时自动创建表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数据保存到postgresql中的表中。我正在使用 spring boot + postgresql 以及 hibernate 。我的应用程序没有任何错误,但它不是在数据库中创建表。



这是我的控制器类

  package com.ge.health .poc.controlleer; 

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ge.health.poc.model.Bookmodel;
import com.ge.health.poc.service.BookServiceImplementation;

@RestController
public class HttpController {

@Autowired
BookServiceImplementation bookserviceimpl;

@RequestMapping(value =/ httpmethod,method = RequestMethod.POST)
@ResponseBody
public void helloService(@RequestBody String input)throws JsonParseException,JsonMappingException,IOException {
System.out.println(input);
ObjectMapper mapper = new ObjectMapper();
Bookmodel pojodata = mapper.readValue(input,Bookmodel.class);

System.out.println(pojodata);


$ b

AppConfig.java

  package com.ge.health.poc.configuration; 

import java.util.Properties;

import javax.annotation.Resource;
import javax.jms.ConnectionFactory;
import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;

公共类AppConfig {

@Resource
私人SettingConfig设置;

@Bean
JmsTemplate jmsTemplate(ConnectionFactory connectionFactory){
return new JmsTemplate(connectionFactory);


@Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(settings.getDriverClassName());
dataSource.setUrl(settings.getDatasource());
dataSource.setUsername(settings.getUsername());
dataSource.setPassword(settings.getPassword());
返回dataSource;
}

/ **
*声明JPA实体管理器工厂。
* /
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();

//休眠属性
属性additionalProperties = new Properties();
additionalProperties.put(hibernate.dialect,settings.getDialect());
additionalProperties.put(hibernate.show_sql,settings.getShowsql());
additionalProperties.put(hibernate.hbm2ddl.auto,settings.getDdlauto());
entityManagerFactory.setJpaProperties(additionalProperties);

返回entityManagerFactory;
}

/ **
*声明事务管理器。
* /
@Bean
public JpaTransactionManager transactionManager(){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory()。getObject());
返回transactionManager;
}
$ b $ **
* PersistenceExceptionTranslationPostProcessor是一个bean后期处理程序
*,它将一个顾问程序添加到任何使用Repository注释的bean中,以便任何
*捕获特定于平台的异常,然后重新生成一个Spring的
* unchecked数据访问异常(即
* DataAccessException的子类)。
* /
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();


$ / code $ / pre

SettingConfig.java

  package com.ge.health.poc.configuration; 

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class SettingConfig {

public String getDdlauto(){
return ddlauto;
}

public void setDdlauto(String ddlauto){
this.ddlauto = ddlauto;
}

public String getShowsql(){
return showsql;
}

public void setShowsql(String showsql){
this.showsql = showsql;
}

public String getDialect(){
return dialect;
}

public void setDialect(String dialect){
this.dialect = dialect;
}

@Value($ {spring.datasource.url})
私有字符串数据源;

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

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

@Value({hibernate.dialect})
private String方言;

@Value($ {spring.datasource.username})
私有字符串用户名;

@Value($ {spring.datasource.password})
私人字符串密码;

@Value($ {spring.datasource.driver-class-name})
private String driverClassName;

public String getDatasource(){
return datasource;
}

public void setDatasource(String datasource){
this.datasource = datasource;
}

public String getUsername(){
return username;
}

public void setUsername(String username){
this.username = username;
}

public String getPassword(){
return password;
}

public void setPassword(String password){
this.password = password;
}

public String getDriverClassName(){
return driverClassName;
}

public void setDriverClassName(String driverClassName){
this.driverClassName = driverClassName;
}

}

application.properties

 #数据库
spring.datasource.driver-class-name = org.postgresql.Driver
spring.datasource.url = jdbc:postgresql:// localhost:5432 / bookdetails
spring.datasource.username = postgres
spring.datasource.password = admin
#Hibernate
hibernate.dialect = org。 hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.hbm2ddl.auto =创建

POJO class

  package com.ge.health.poc.model; 

import javax.persistence.Column;
import javax.persistence.Table;

import org.springframework.data.annotation.Id;
import org.springframework.stereotype.Component;

@Component
@Table
public class Bookmodel {

@Id
private String id;
@Column
私人字符串名称;
@Column
private String isbn;
@Column
私人字符串作者;
@Column
私人字符串页面;

public String getId(){
return id;
}

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

public String getPages(){
return pages;
}

public void setPages(String pages){
this.pages = pages;

$ b @Override
public String toString(){
returnBookmodel [id =+ id +,name =+ name +,isbn =+ isbn +,author =+ author +,pages =+ pages
+];
}

public String getName(){
return name;
}

public void setName(String name){
this.name = name;
}

public String getIsbn(){
return isbn;
}

public void setIsbn(String isbn){
this.isbn = isbn;
}

public String getAuthor(){
return author;
}

public void setAuthor(String author){
this.author = author;
}

}

我想将数据保存到表postgresql.I使用spring boot + postgresql和hibernate。我的应用程序没有任何错误,但它并没有在数据库中创建表。 你是使用Spring Boot和第一个你做的事情是非常努力地不使用Spring Boot。

不用自己完成所有的配置,而是让Spring Boot为您完成繁重的工作。

在你的 application.properties 中设置正确的方言并使用正确的属性(参见Spring Boot参考指南的本节获取完整列表的属性)。

 #数据库
spring.datasource.driver-class-name = org.postgresql.Driver
spring .datasource.url = jdbc:postgresql:// localhost:5432 / bookdetails
spring.datasource.username = postgres
spring.datasource.password = admin
$ b $ Hibernate
spring.jpa.database = org.hibernate.dialect.PostgreSQL94Dialect
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = create

然后移除您的自定义配置(即 AppConfig SettingConfig ),它打破了Spring Boot的自动配置。

I want to save data to a table in postgresql. I am using spring boot + postgresql along with hibernate. My Application does not have any error but it is not creating table in database.

This is my controller class

    package com.ge.health.poc.controlleer;

    import java.io.IOException;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.RestController;

    import com.fasterxml.jackson.core.JsonParseException;
    import com.fasterxml.jackson.databind.JsonMappingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.ge.health.poc.model.Bookmodel;
    import com.ge.health.poc.service.BookServiceImplementation;

    @RestController
    public class HttpController {

        @Autowired
        BookServiceImplementation bookserviceimpl;

        @RequestMapping(value = "/httpmethod", method = RequestMethod.POST)
        @ResponseBody
        public void helloService(@RequestBody String input) throws JsonParseException, JsonMappingException, IOException {
            System.out.println(input);
            ObjectMapper mapper = new ObjectMapper();
            Bookmodel pojodata = mapper.readValue(input, Bookmodel.class);

            System.out.println(pojodata);

        }
    }

AppConfig.java

    package com.ge.health.poc.configuration;

    import java.util.Properties;

    import javax.annotation.Resource;
    import javax.jms.ConnectionFactory;
    import javax.sql.DataSource;

    import org.springframework.context.annotation.Bean;
    import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
    import org.springframework.jdbc.datasource.DriverManagerDataSource;
    import org.springframework.jms.core.JmsTemplate;
    import org.springframework.orm.jpa.JpaTransactionManager;
    import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;

    public class AppConfig {

        @Resource
        private SettingConfig settings;

        @Bean
        JmsTemplate jmsTemplate(ConnectionFactory connectionFactory) {
            return new JmsTemplate(connectionFactory);
        }

        @Bean
        public DataSource dataSource() {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName(settings.getDriverClassName());
            dataSource.setUrl(settings.getDatasource());
            dataSource.setUsername(settings.getUsername());
            dataSource.setPassword(settings.getPassword());
            return dataSource;
        }

        /**
         * Declare the JPA entity manager factory.
         */
        @Bean
        public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
            LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();

            // Hibernate properties
            Properties additionalProperties = new Properties();
            additionalProperties.put("hibernate.dialect", settings.getDialect());
            additionalProperties.put("hibernate.show_sql", settings.getShowsql());
            additionalProperties.put("hibernate.hbm2ddl.auto", settings.getDdlauto());
            entityManagerFactory.setJpaProperties(additionalProperties);

            return entityManagerFactory;
        }

        /**
         * Declare the transaction manager.
         */
        @Bean
        public JpaTransactionManager transactionManager() {
            JpaTransactionManager transactionManager = new JpaTransactionManager();
            transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
            return transactionManager;
        }

        /**
         * PersistenceExceptionTranslationPostProcessor is a bean post processor
         * which adds an advisor to any bean annotated with Repository so that any
         * platform-specific exceptions are caught and then rethrown as one Spring's
         * unchecked data access exceptions (i.e. a subclass of
         * DataAccessException).
         */
        @Bean
        public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
            return new PersistenceExceptionTranslationPostProcessor();
        }
    }

SettingConfig.java

    package com.ge.health.poc.configuration;

    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;

    @Component
    public class SettingConfig {

        public String getDdlauto() {
            return ddlauto;
        }

        public void setDdlauto(String ddlauto) {
            this.ddlauto = ddlauto;
        }

        public String getShowsql() {
            return showsql;
        }

        public void setShowsql(String showsql) {
            this.showsql = showsql;
        }

        public String getDialect() {
            return dialect;
        }

        public void setDialect(String dialect) {
            this.dialect = dialect;
        }

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

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

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

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

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

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

        @Value("${spring.datasource.driver-class-name}")
        private String driverClassName;

        public String getDatasource() {
            return datasource;
        }

        public void setDatasource(String datasource) {
            this.datasource = datasource;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getDriverClassName() {
            return driverClassName;
        }

        public void setDriverClassName(String driverClassName) {
            this.driverClassName = driverClassName;
        }

    }

application.properties

    # Database
    spring.datasource.driver-class-name=org.postgresql.Driver
    spring.datasource.url=jdbc:postgresql://localhost:5432/bookdetails
    spring.datasource.username=postgres
    spring.datasource.password=admin
    # Hibernate
    hibernate.dialect=org.hibernate.dialect.MySQLDialect
    hibernate.show_sql=true
    hibernate.hbm2ddl.auto=create

POJO class

package com.ge.health.poc.model;

import javax.persistence.Column;
import javax.persistence.Table;

import org.springframework.data.annotation.Id;
import org.springframework.stereotype.Component;

@Component
@Table
public class Bookmodel {

    @Id
    private String id;
    @Column
    private String name;
    @Column
    private String isbn;
    @Column
    private String author;
    @Column
    private String pages;

    public String getId() {
        return id;
    }

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

    public String getPages() {
        return pages;
    }

    public void setPages(String pages) {
        this.pages = pages;
    }

    @Override
    public String toString() {
        return "Bookmodel [id=" + id + ", name=" + name + ", isbn=" + isbn + ", author=" + author + ", pages=" + pages
                + "]";
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

}

I want to save data to a table in postgresql.I am using spring boot + postgresql along with hibernate. My Application donot have any error but it is not creating table in database.

解决方案

You are "using" Spring Boot and the first thing you do is try very hard not to use Spring Boot.

Instead of doing all the configuration by yourself let Spring Boot do the heavy lifting for you.

In your application.properties set the proper dialect and use the correct properties (see this section of the Spring Boot Reference Guide for a full list of properties).

# Database
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/bookdetails
spring.datasource.username=postgres
spring.datasource.password=admin

# Hibernate
spring.jpa.database=org.hibernate.dialect.PostgreSQL94Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create

And remove your custom configuration (i.e. the AppConfig and SettingConfig) that breaks the auto configuration of Spring Boot.

这篇关于休眠不使用postgresql在Spring启动时自动创建表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆