Spring-Hibernate-mvc自动表创建失败

时间:2017-03-14 06:35:33

标签: java spring hibernate model-view-controller

即使数据库存在于后端......在执行spring-hibernate-cf文件时,它会导致以下异常......

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:表' school.customer'不存在

注意:我没有使用H2 DB BUILDER ..

以下是我的Customer.java pojo:

    package org.springsource.cloudfoundry.mvc.services;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Date;

@Entity
public class Customer implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

@NotNull
private Date signupDate;

@NotNull
private String firstName;

@NotNull
private String lastName;

public Integer getId() {
    return id;
}

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

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public Date getSignupDate() {
    return signupDate;
}

public void setSignupDate(Date signupDate) {
    this.signupDate = signupDate;
}
}

以下是CustomerService.java:

     package org.springsource.cloudfoundry.mvc.services;

  import org.springframework.cache.annotation.CacheEvict;
  import org.springframework.cache.annotation.Cacheable;
  import org.springframework.stereotype.Service;
  import org.springframework.transaction.annotation.Transactional;

  import javax.persistence.EntityManager;
  import javax.persistence.PersistenceContext;
  import java.util.Collection;
  import java.util.Date;
  import java.util.List;

  @Service
  @SuppressWarnings("unchecked")
  @Transactional
  public class CustomerService {

static private final String CUSTOMERS_REGION = "customers";

@PersistenceContext
private EntityManager em;

 public Customer createCustomer(String firstName, String lastName, Date signupDate) {
    Customer customer = new Customer();
    customer.setFirstName(firstName);
    customer.setLastName(lastName);
    customer.setSignupDate(signupDate);
    em.persist(customer);
    return customer;
 }

 public Collection<Customer> search(String name) {
    String sqlName = ("%" + name + "%").toLowerCase();
    String sql = "select c.* from customer c where (LOWER( c.firstName ) LIKE :fn OR LOWER( c.lastName ) LIKE :ln)";
    return em.createNativeQuery(sql, Customer.class)
            .setParameter("fn", sqlName)
            .setParameter("ln", sqlName)
            .getResultList();
        }


 @Transactional(readOnly = true)
 public List<Customer> getAllCustomers() {
    return em.createQuery("SELECT * FROM " +   Customer.class.getName()).getResultList();
  }


@Cacheable(CUSTOMERS_REGION)
@Transactional(readOnly = true)
public Customer getCustomerById(Integer id) {
    return em.find(Customer.class, id);
}

@CacheEvict(CUSTOMERS_REGION)
public void deleteCustomer(Integer id) {
    Customer customer = getCustomerById(id);
    em.remove(customer);
}

@CacheEvict(value = CUSTOMERS_REGION, key = "#id")
public void updateCustomer(Integer id, String fn, String ln, Date birthday)         {
    Customer customer = getCustomerById(id);
    customer.setLastName(ln);
    customer.setSignupDate(birthday);
    customer.setFirstName(fn);
    //sessionFactory.getCurrentSession().update(customer);
    em.merge(customer);
    }
   }

CONFIG.properties

    debug = true
    ds.driverClass = com.mysql.jdbc.Driver
    ds.url= jdbc:mysql://localhost:3306/school
    ds.user=root
    ds.password=

LocalDataSourceConfiguration.java

     package org.springsource.cloudfoundry.mvc.services.config;


 import org.apache.commons.dbcp.BasicDataSource;
 import org.hibernate.dialect.H2Dialect;
 import org.hibernate.ejb.HibernatePersistence;
 import org.springframework.cache.Cache;
 import org.springframework.cache.CacheManager;
  import org.springframework.cache.concurrent.ConcurrentMapCache;
 import org.springframework.cache.support.SimpleCacheManager;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.context.annotation.Profile;
 import org.springframework.core.env.Environment;
  import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;

import org.springsource.cloudfoundry.mvc.services.Customer;

import com.mysql.jdbc.Driver;

 import javax.sql.DataSource;
 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.Map;

@Configuration
@Profile("default")
public class LocalDataSourceConfiguration   {


@Bean
public DataSource dataSource( Environment environment ) throws Exception {

    /*return new EmbeddedDatabaseBuilder()
            .setName("crm")
            .setType(EmbeddedDatabaseType.H2)
            .build();*/


    String user = environment.getProperty("ds.user"),
            pw = environment.getProperty("ds.password"),
            url = environment.getProperty("ds.url");
    Class<Driver> driverClass = environment.getPropertyAsClass( "ds.driverClass", Driver.class );

    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName( driverClass.getName() );
    basicDataSource.setPassword( pw );
    basicDataSource.setUrl( url );
    basicDataSource.setUsername( user );
    basicDataSource.setInitialSize( 5 );
    basicDataSource.setMaxActive( 10 );
    return basicDataSource;

}

@Bean
public LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean( DataSource dataSource  ) throws Exception {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource( dataSource );
    em.setPackagesToScan(Customer.class.getPackage().getName());
    em.setPersistenceProvider(new HibernatePersistence());
    Map<String, String> p = new HashMap<String, String>();
    p.put(org.hibernate.cfg.Environment.HBM2DDL_AUTO, "create");
    p.put(org.hibernate.cfg.Environment.HBM2DDL_IMPORT_FILES, "import_h2.sql");
    p.put(org.hibernate.cfg.Environment.DIALECT, H2Dialect.class.getName());
    p.put(org.hibernate.cfg.Environment.SHOW_SQL, "true");
    em.setJpaPropertyMap(p);
    return em;
   }

  @Bean
  public CacheManager cacheManager() throws Exception {
    SimpleCacheManager scm = new SimpleCacheManager();
    Cache cache = new ConcurrentMapCache("customers");
    scm.setCaches(Arrays.asList(cache));
    return scm;
   }

   }

CloudFoundryDataSourceConfiguration.java

   package org.springsource.cloudfoundry.mvc.services.config;

   import java.util.HashMap;
   import java.util.Map;

     import javax.sql.DataSource;

   import org.hibernate.dialect.PostgreSQLDialect;
   import org.hibernate.ejb.HibernatePersistence;
   import org.springframework.cache.CacheManager;
   import org.springframework.cloud.config.java.AbstractCloudConfig;
    import org.springframework.context.annotation.Bean;
   import org.springframework.context.annotation.Configuration;
  import org.springframework.context.annotation.Profile;
   import org.springframework.data.redis.cache.RedisCacheManager;
   import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
   import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
     import org.springsource.cloudfoundry.mvc.services.Customer;

  @Configuration
  @Profile("cloud")
 public class CloudFoundryDataSourceConfiguration extends AbstractCloudConfig  {

   @Bean
     public DataSource dataSource() {
        return connectionFactory().dataSource();
     }

@Bean
public RedisConnectionFactory redisConnectionFactory() {
    return connectionFactory().redisConnectionFactory();
}

@Bean
public RedisTemplate<String, Object> redisTemplate() throws Exception {
    RedisTemplate<String, Object> ro = new RedisTemplate<String, Object>();
    ro.setConnectionFactory(redisConnectionFactory());
    return ro;
}


   @Bean
  public LocalContainerEntityManagerFactoryBean   localContainerEntityManagerFactoryBean( DataSource dataSource  ) throws Exception {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource( dataSource );
    em.setPackagesToScan(Customer.class.getPackage().getName());
    em.setPersistenceProvider(new HibernatePersistence());
    Map<String, String> p = new HashMap<String, String>();
    p.put(org.hibernate.cfg.Environment.HBM2DDL_AUTO, "create");
    p.put(org.hibernate.cfg.Environment.HBM2DDL_IMPORT_FILES, "import_psql.sql");
    p.put(org.hibernate.cfg.Environment.DIALECT, PostgreSQLDialect.class.getName());
    p.put(org.hibernate.cfg.Environment.SHOW_SQL, "true");
    em.setJpaPropertyMap(p);
    return em;
    }

  @Bean
  public CacheManager cacheManager() throws Exception {
    return new RedisCacheManager(redisTemplate());
     }

   }

的pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0   http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>org.springsource.cloudfoundry.mvc</groupId>
   <artifactId>web</artifactId>
    <name>A Spring / Cloud Foundry Template</name>
    <packaging>war</packaging>
    <version>1.0.0</version>

  <properties>
    <java-version>1.6</java-version>
    <org.springframework-version>3.2.4.RELEASE</org.springframework-version>
    <jackson.version>2.2.2</jackson.version>
    <spring-cloud.version>1.0.1.BUILD-SNAPSHOT</spring-cloud.version>
</properties>
<dependencies>
    <!-- CloudFoundry -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-cloudfoundry-connector</artifactId>
        <version>${spring-cloud.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-localconfig-connector</artifactId>
        <version>${spring-cloud.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-spring-service-connector</artifactId>
        <version>${spring-cloud.version}</version>
    </dependency>

    <dependency>
        <groupId>postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.1-901-1.jdbc4</version>
    </dependency>
    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.4</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-redis</artifactId>
        <version>1.0.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring3</artifactId>
        <version>2.0.6</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.5.6</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.5.6</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.0.0.Final</version>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.3.162</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.web</groupId>
        <artifactId>jstl-impl</artifactId>
        <version>1.2</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.0.0.GA</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.8.1</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>4.0.0.GA</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>servlet-api</artifactId>
        <version>3.0.20100224</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>2.2.2</version>
    </dependency>
</dependencies>
<repositories>
    <repository>
        <id>repository.springframework.maven.milestone</id>
        <name>Spring Framework Maven Milestone Repository</name>
        <url>http://maven.springframework.org/milestone</url>
    </repository>
    <repository>
        <id>repository.springframework.maven.snapshot</id>
        <name>Spring Framework Maven Milestone Repository</name>
        <url>http://maven.springframework.org/snapshot</url>
    </repository>
</repositories>
<pluginRepositories>
    <pluginRepository>
        <id>repository.springframework.maven.milestone</id>
        <name>Spring Framework Maven Milestone Repository</name>
        <url>http://maven.springframework.org/milestone</url>
    </pluginRepository>
</pluginRepositories>
<build>

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>${java-version}</source>
                <target>${java-version}</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.1.1</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
    </plugins>
    </build>

    </project>

1 个答案:

答案 0 :(得分:0)

我认为问题是你在这里使用H2Dialect连接到MySQL数据库:

p.put(org.hibernate.cfg.Environment.DIALECT, H2Dialect.class.getName());