Hibernate не находит таблицу/бд H2 Embedded Mode

188
04 декабря 2017, 16:48

applicationContext:

     <?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:jdbc="http://www.springframework.org/schema/jdbc"
   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.xsd 
   http://www.springframework.org/schema/jdbc 
   http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<!-- XML Bean Definitions -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.h2.Driver" />
    <property name="url" value="jdbc:h2:mem://localhost/test" />
    <property name="username" value="sa" />
    <property name="password" value="" />
</bean>
<!-- initialize Embedded DataSource. Встроенная база данных-->
<jdbc:initialize-database data-source="dataSource">
    <jdbc:script location="classpath:dbschema.sql"/>
    <jdbc:script location="classpath:test-data.sql"/>
</jdbc:initialize-database>
<!--Do not forget activate @Transactional JPA annotation with <annotation-driven/>-->
<!-- JPA Persistence Context and EntityManager configuration -->
<bean id="entityManagerFactory"
      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
    <!--packagesToScan - search Entity and mapping them -->
    <property name="packagesToScan" value="main" />
    <property name="dataSource" ref="dataSource" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" >
            <property name="generateDdl" value="true" />
            <property name="showSql" value="true" />
        </bean>
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.format_sql">false</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>
</bean>
<!-- Automatic Transaction Participation-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

DAO:

   @Repository
   @Transactional
   public class ORMService {
@PersistenceContext
private EntityManager entityManager;
public List<User> queryFindAllUsersJPA() {
    System.out.println("ORMService queryfindAllUsersJPA is called");
    String query = "from User";
    TypedQuery<User> typedQuery = entityManager.createQuery(query, User.class);
    return typedQuery.getResultList();
}

}

DataSet

 @Entity
 @Table(name = "USER")
 public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "IDUSER")
private int idUser;
@NotEmpty
@Size(min = 5, max = 20)
@Column(name = "USERNAME")
private String username;
@NotEmpty
@Size(min=5, max=20)
@Column(name="PASSWORD")
private String password;
@Column(name="ENABLED")
private boolean enabled;
public int getIdUser() {
    return idUser;
}
public void setIdUser(int idUser) {
    this.idUser = idUser;
}
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 boolean isEnabled() {
    return enabled;
}
public void setEnabled(boolean enabled) {
    this.enabled = enabled;
}
@Override
public String toString() {
    return "User{" +
            "idUser=" + idUser +
            ", username='" + username + '\'' +
            ", password='" + password + '\'' +
            ", enabled=" + enabled +
            '}';
}
}

dbschema.sql

   DROP TABLE IF EXISTS USER;
 --USER TABLE
CREATE TABLE IF NOT EXISTS USER (
IDUSER INT NOT NULL AUTO_INCREMENT,
USERNAME VARCHAR(255) NOT NULL ,
PASSWORD  VARCHAR(255) NOT NULL,
ENABLED BOOLEAN NOT NULL,PRIMARY KEY(IDUSER)
);

Controller

   @RestController
public class MainController {
@Autowired
private ORMService ormService;
@GetMapping(value = "/")
public ModelAndView getAllUsers() {
    System.out.println("ORMController ormFindAllUsers is called");
    List<User> users = ormService.queryFindAllUsersJPA();
    return new ModelAndView("index", "resultObject", users);
}
}

log

    ORMController ormFindAllUsers is called
    ORMService queryfindAllUsersJPA is called
    03-Dec-2017 18:18:43.982 INFO [http-nio-8080-exec-1] 
  org.hibernate.hql.internal.QueryTranslatorFactoryInitiator.initiateService 
    HHH000397: Using ASTQueryTranslatorFactory
    03-Dec-2017 18:18:44.216 WARN [http-nio-8080-exec-1] 
    org.hibernate.engine.jdbc.spi.SqlExceptionHelper.logExceptions SQL 
   Error: 42102, SQLState: 42S02
   03-Dec-2017 18:18:44.216 ERROR [http-nio-8080-exec-1] 
   org.hibernate.engine.jdbc.spi.SqlExceptionHelper.logExceptions Таблица 
   "USER" не найдена
   Table "USER" not found; SQL statement:
   select user0_.IDUSER as IDUSER1_0_, user0_.ENABLED as ENABLED2_0_, 
   user0_.PASSWORD as PASSWORD3_0_, user0_.USERNAME as USERNAME4_0_ from 
   USER user0_ [42102-196]
   Hibernate: select user0_.IDUSER as IDUSER1_0_, user0_.ENABLED as 
   ENABLED2_0_, user0_.PASSWORD as PASSWORD3_0_, user0_.USERNAME as 
   USERNAME4_0_ from USER user0_
Answer 1

jdbc:h2:mem указывает на базу данных в памяти, а не в файле

Вам судя по пути к базе нужен сервер мод:

Embedded:
jdbc:h2:~/test 'test' in the user home directory
jdbc:h2:/data/test 'test' in the directory /data
jdbc:h2:test in the current(!) working directory
In-Memory:
jdbc:h2:mem:test multiple connections in one process
jdbc:h2:mem: unnamed private; one connection
Server Mode:
jdbc:h2:tcp://localhost/~/test user home dir
jdbc:h2:tcp://localhost//data/test absolute dir
Server start:java -cp *.jar org.h2.tools.Server

источник

READ ALSO
Вывод в jTextArea из другого класса

Вывод в jTextArea из другого класса

Доброго времени сутокЕсть два класса

170
Покажите как возникает spurious wakeup

Покажите как возникает spurious wakeup

Может кто-нибудь по шагам показать как возникает spurious wakeup? Те

155
Передача переменной из receiver&#39;a в другой класс

Передача переменной из receiver'a в другой класс

Есть broadcast receiver, нужно из него передать String number в обычный класс MainActivityКак это сделать?

128
OutOfMemoryError: Java heap space при обычном вызове метода

OutOfMemoryError: Java heap space при обычном вызове метода

При повторном вызове programMenu(); и добавлении нового элемента в список - вылетает Exeption:

181