Relation "xxxx" does not exist - java

Can you tell me how to fix this exception from console?
org.postgresql.util.PSQLException: ERROR: relation "xxxx" does not exist
This exception is for some tables in my project, and I don't know why. Application works fine without any issues. I have in resources import script dml and tables are filled as well.
Here is my sample implementation table:
#Entity
#Table(name = "USERS")
public class User extends Abstract {
#Column(name = "FIRST_NAME", nullable = false, length = 100)
private String firstName;
#Column(name = "LAST_NAME", nullable = false, length = 100)
private String lastName;
#Column(name = "EMAIL", nullable = false, length = 100)
private String email;
#Column(name = "PASSWORD", nullable = false, length = 60)
private String password;
#Column(name = "PHONE_NUMBER", nullable = false, length = 20)
private String phoneNumber;
#Column(name = "BIRTHDATE", nullable = false, columnDefinition = "TIMESTAMP")
private LocalDateTime birthdate;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(
name = "USERS_CONTACTS",
joinColumns = #JoinColumn(name = "USER_ID",
foreignKey = #ForeignKey(name = "FK__USERS__USERS__USER_ID")),
inverseJoinColumns = #JoinColumn(name = "CONTACT_ID",
foreignKey = #ForeignKey(name = "FK__USERS__USERS__CONTACT_ID")))
private List<User> contacts;
// getters and setters
}
and abstract class:
#MappedSuperclass
public class Abstract {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID", columnDefinition = "serial")
private Long id;
#Column(name = "CREATED_ON", nullable = false, columnDefinition = "TIMESTAMP")
private LocalDateTime createdOn;
}
Here is full console log:
Hibernate: alter table users_contacts drop constraint FK__USERS__USERS__USER_ID
2018-01-22 15:57:32.177 WARN 28193 --- [ main] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlString(SchemaDropperImpl.java:375) [hibernate-core-5.2.12.Final.jar:5.2.12.Final]
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlStrings(SchemaDropperImpl.java:359) [hibernate-core-5.2.12.Final.jar:5.2.12.Final]
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applyConstraintDropping(SchemaDropperImpl.java:331) [hibernate-core-5.2.12.Final.jar:5.2.12.Final]
at org.hibernate.tool.schema.internal.SchemaDropperImpl.dropFromMetadata(SchemaDropperImpl.java:230) [hibernate-core-5.2.12.Final.jar:5.2.12.Final]
at org.hibernate.tool.schema.internal.SchemaDropperImpl.performDrop(SchemaDropperImpl.java:154) [hibernate-core-5.2.12.Final.jar:5.2.12.Final]
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:126) [hibernate-core-5.2.12.Final.jar:5.2.12.Final]
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:112) [hibernate-core-5.2.12.Final.jar:5.2.12.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:144) [hibernate-core-5.2.12.Final.jar:5.2.12.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72) [hibernate-core-5.2.12.Final.jar:5.2.12.Final]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:313) [hibernate-core-5.2.12.Final.jar:5.2.12.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:452) [hibernate-core-5.2.12.Final.jar:5.2.12.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:889) [hibernate-core-5.2.12.Final.jar:5.2.12.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) [spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:360) [spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:382) [spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:371) [spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:336) [spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) [spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) [spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) [spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) [spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) [spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) [spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) [spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) [spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1080) [spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857) [spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) [spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at sk.moe.zoya.ZoyaApplication.main(ZoyaApplication.java:10) [classes/:na]
Caused by: org.postgresql.util.PSQLException: ERROR: relation "users_contacts" does not exist
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2455) ~[postgresql-9.4.1212.jre7.jar:9.4.1212.jre7]
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2155) ~[postgresql-9.4.1212.jre7.jar:9.4.1212.jre7]
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:288) ~[postgresql-9.4.1212.jre7.jar:9.4.1212.jre7]
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:430) ~[postgresql-9.4.1212.jre7.jar:9.4.1212.jre7]
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:356) ~[postgresql-9.4.1212.jre7.jar:9.4.1212.jre7]
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:303) ~[postgresql-9.4.1212.jre7.jar:9.4.1212.jre7]
at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:289) ~[postgresql-9.4.1212.jre7.jar:9.4.1212.jre7]
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:266) ~[postgresql-9.4.1212.jre7.jar:9.4.1212.jre7]
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:262) ~[postgresql-9.4.1212.jre7.jar:9.4.1212.jre7]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_151]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_151]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_151]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_151]
at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114) ~[tomcat-jdbc-8.5.23.jar:na]
at com.sun.proxy.$Proxy81.execute(Unknown Source) ~[na:na]
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
... 35 common frames omitted
Hibernate: drop table if exists feeds cascade
2018-01-22 15:57:32.178 WARN 28193 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 0, SQLState: 00000
2018-01-22 15:57:32.178 WARN 28193 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : table "feeds" does not exist, skipping
Hibernate: drop table if exists messages cascade
2018-01-22 15:57:32.178 WARN 28193 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 0, SQLState: 00000
2018-01-22 15:57:32.178 WARN 28193 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : table "messages" does not exist, skipping
Hibernate: drop table if exists threads cascade
2018-01-22 15:57:32.179 WARN 28193 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 0, SQLState: 00000
2018-01-22 15:57:32.179 WARN 28193 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : table "threads" does not exist, skipping
Hibernate: drop table if exists users cascade
2018-01-22 15:57:32.179 WARN 28193 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 0, SQLState: 00000
2018-01-22 15:57:32.179 WARN 28193 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : table "users" does not exist, skipping
Hibernate: drop table if exists users_contacts cascade
2018-01-22 15:57:32.179 WARN 28193 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 0, SQLState: 00000
2018-01-22 15:57:32.179 WARN 28193 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : table "users_contacts" does not exist, skipping
Hibernate: create table feeds (id bigserial not null, created_on TIMESTAMP not null, feed_text varchar(255), sender_id serial not null, primary key (id))
Hibernate: create table messages (id bigserial not null, created_on TIMESTAMP not null, msg_text varchar(255) not null, sender_id serial not null, thread_id serial not null, primary key (id))
Hibernate: create table threads (id bigserial not null, created_on TIMESTAMP not null, participant_one_id serial not null, participant_two_id serial not null, primary key (id))
Hibernate: create table users (id bigserial not null, created_on TIMESTAMP not null, active boolean not null, birthdate TIMESTAMP not null, city varchar(100) not null, country varchar(3) not null, email varchar(100) not null, first_name varchar(100) not null, gender varchar(255) not null, last_name varchar(100) not null, password varchar(60) not null, phone_number varchar(20) not null, picture_url varchar(255), updated_on TIMESTAMP not null, verified boolean not null, primary key (id))
Hibernate: create table users_contacts (user_id serial not null, contact_id serial not null)
Hibernate: alter table feeds add constraint FK__USERS__FEEDS__SENDER_ID foreign key (sender_id) references users
Hibernate: alter table messages add constraint FK__THREADS__USERS__SENDER_ID foreign key (sender_id) references users
Hibernate: alter table messages add constraint FK__THREADS__MESSAGES__THREAD_ID foreign key (thread_id) references threads
Hibernate: alter table threads add constraint FK__USERS__THREADS__PARTICIPANT_ONE_ID foreign key (participant_one_id) references users
Hibernate: alter table threads add constraint FK__USERS__THREADS__PARTICIPANT_TWO_ID foreign key (participant_two_id) references users
Hibernate: alter table users_contacts add constraint FK__USERS__USERS__CONTACT_ID foreign key (contact_id) references users
Hibernate: alter table users_contacts add constraint FK__USERS__USERS__USER_ID foreign key (user_id) references users
2018-01-22 15:57:32.235 INFO 28193 --- [ main] o.h.t.schema.internal.SchemaCreatorImpl : HHH000476: Executing import script 'ScriptSourceInputFromUrl(file:/home/martin/Workspace/zoya/target/classes/import.sql)'

Related

SQLSyntaxErrorException in JPA One to many relationship

I have two entity classes, Order class and OrderLineItems class. I am trying to create a one-many relationship between Order and OrderLineItems, i.e One Order can have multiple OrderLineItems. The code I have is given below.
#Entity
#Table(name = "order")
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#Builder
public class Order {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long orderId;
private String orderNumber;
#OneToMany(mappedBy = "order")
private List<OrderLineItems> orderLineItems;
}
#Entity
#Getter
#Setter
#Table(name = "order_line_items")
#AllArgsConstructor
#NoArgsConstructor
#Builder
public class OrderLineItems {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long orderLineItemsId;
private String skuCode;
private BigDecimal price;
private Integer quantity;
#ManyToOne(optional = false)
private Order order;
}
The above code results in a SqlSyntaxErrorException. The relevant part of trace is given below. What am I doing wrong?
2022-04-16 12:39:22.643 INFO 85559 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
Hibernate: create table order (order_id bigint not null auto_increment, order_number varchar(255), primary key (order_id)) engine=InnoDB
2022-04-16 12:39:23.098 WARN 85559 --- [ main] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL "create table order (order_id bigint not null auto_increment, order_number varchar(255), primary key (order_id)) engine=InnoDB" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table order (order_id bigint not null auto_increment, order_number varchar(255), primary key (order_id)) engine=InnoDB" via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:581) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:526) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.createTable(AbstractSchemaMigrator.java:293) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.java:74) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:220) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:123) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:196) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:85) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:335) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:471) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1498) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.18.jar:5.3.18]
.............
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order (order_id bigint not null auto_increment, order_number varchar(255), prima' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.28.jar:8.0.28]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.28.jar:8.0.28]
at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:763) ~[mysql-connector-java-8.0.28.jar:8.0.28]
at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:648) ~[mysql-connector-java-8.0.28.jar:8.0.28]
at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:94) ~[HikariCP-4.0.3.jar:na]
at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-4.0.3.jar:na]
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
... 34 common frames omitted
#Table(name = "order"): order is reserved word in MySQL. Change table name to something else, f.e. "orders" and it will work :)

Caused by: org.postgresql.util.PSQLException: ERROR: type "enum" does not exist

I am using Spring Data JPA, Spring Boot 2.1.6.RELEASE + Postgres 11.0 and Lombok example. In this example, while creating the schema following error is coming.
I am getting below error.
Hibernate:
drop table if exists test.student cascade
2019-07-09 15:23:17.055 WARN 14860 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Warning Code: 0, SQLState: 00000
2019-07-09 15:23:17.056 WARN 14860 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : table "student" does not exist, skipping
Hibernate:
create table test.student (
student_id bigserial not null,
crte_user_id varchar(30) not null,
crte_ts TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP not null,
lst_updt_ts TIMESTAMP WITHOUT TIME ZONE not null,
lst_updt_user_id varchar(30),
status ENUM('A', 'I'),
student_name varchar(255) not null,
primary key (student_id)
)
2019-07-09 15:23:17.065 WARN 14860 --- [ main] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL "
create table test.student (
student_id bigserial not null,
crte_user_id varchar(30) not null,
crte_ts TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP not null,
lst_updt_ts TIMESTAMP WITHOUT TIME ZONE not null,
lst_updt_user_id varchar(30),
status ENUM('A', 'I'),
student_name varchar(255) not null,
primary key (student_id)
)" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "
create table test.student (
student_id bigserial not null,
crte_user_id varchar(30) not null,
crte_ts TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP not null,
lst_updt_ts TIMESTAMP WITHOUT TIME ZONE not null,
lst_updt_user_id varchar(30),
status ENUM('A', 'I'),
student_name varchar(255) not null,
primary key (student_id)
)" via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:440) [hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreatorImpl.java:424) [hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:315) [hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:166) [hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:135) [hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:121) [hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:155) [hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72) [hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:310) [hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:467) [hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:939) [hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) [spring-orm-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) [spring-orm-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390) [spring-orm-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) [spring-orm-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) [spring-orm-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837) [spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774) [spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) [spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) [spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) [spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) [spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) [spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105) ~[spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:742) ~[spring-boot-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:389) ~[spring-boot-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:311) ~[spring-boot-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1213) ~[spring-boot-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1202) ~[spring-boot-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at com.example.MyProgramApplication.main(MyProgramApplication.java:17) ~[classes/:na]
Caused by: org.postgresql.util.PSQLException: ERROR: type "enum" does not exist
Position: 314
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440) ~[postgresql-42.2.5.jar:42.2.5]
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183) ~[postgresql-42.2.5.jar:42.2.5]
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308) ~[postgresql-42.2.5.jar:42.2.5]
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441) ~[postgresql-42.2.5.jar:42.2.5]
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365) ~[postgresql-42.2.5.jar:42.2.5]
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:307) ~[postgresql-42.2.5.jar:42.2.5]
at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:293) ~[postgresql-42.2.5.jar:42.2.5]
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:270) ~[postgresql-42.2.5.jar:42.2.5]
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:266) ~[postgresql-42.2.5.jar:42.2.5]
at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:95) ~[HikariCP-3.2.0.jar:na]
at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-3.2.0.jar:na]
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
... 34 common frames omitted
Student.java
#Builder
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(uniqueConstraints = {
#UniqueConstraint(name="student_name_key",columnNames = {"studentName"})
})
public class Student extends AuditEntity{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "student_id")
private Long studentId;
#Column(name = "studentName", nullable = false)
private String studentName;
#Builder(builderMethodName = "sBuilder")
public Student(String studentName, Instant createdDate, Instant lastUpdateDate, String createUser,
String lastUpdateUser, String status) {
super(createdDate, lastUpdateDate, createUser, lastUpdateUser, status);
this.studentName = studentName;
}
}
AuditEntity.java
#Data
#NoArgsConstructor
#AllArgsConstructor
#MappedSuperclass
#EntityListeners(AuditingEntityListener.class)
public class AuditEntity {
#CreatedDate
#Column(name = "createdDate", nullable = false, updatable = false, columnDefinition = "TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP")
private Instant createdDate;
#LastModifiedDate
#Column(name = "lastUpdateDate", nullable = false, columnDefinition = "TIMESTAMP WITHOUT TIME ZONE")
private Instant lastUpdateDate;
#Column(name = "createUser", nullable = false, length = 30)
private String createUser;
#Column(name = "lastUpdateUser", length = 30)
private String lastUpdateUser;
#Column(name = "status", length = 1, columnDefinition = "ENUM('A', 'I')")
private String status;
}
MainApp.java
#SpringBootApplication
public class MainApp implements CommandLineRunner {
#Autowired
ProgramRepository programRepository;
public static void main(String[] args) {
SpringApplication.run(MainApp.class, args);
}
#Override
public void run(String... args) throws Exception {
Student student = Student.sBuilder().studentName("John Doe").createUser("ABC")
.createdDate(Instant.now()).lastUpdateDate(Instant.now()).lastUpdateUser("XYZ").build();
programRepository.save(student);
}
}
Note: I am really looking to apply constraint on the private String status; to accept either A or I. Any values apart from this should not allowed. If I remove columnDefinition = "ENUM('A', 'I')"then things works just works fine. Why?
Is this a bug ?
I think here is what you need:
CREATE TYPE month AS ENUM ('January', 'February', 'March', 'and so on...');
CREATE TABLE magazine(
id serial PRIMARY KEY,
title text NOT NULL,
issue_month month,
issue_year integer
);
Check out this post for more:)
Create a ENUM and use as below :
#Data
#NoArgsConstructor
#AllArgsConstructor
#MappedSuperclass
#EntityListeners(AuditingEntityListener.class)
public class AuditEntity {
public static enum Status {
A, I
}
#CreatedDate
#Column(name = "createdDate", nullable = false, updatable = false, columnDefinition = "TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP")
private Instant createdDate;
#LastModifiedDate
#Column(name = "lastUpdateDate", nullable = false, columnDefinition = "TIMESTAMP WITHOUT TIME ZONE")
private Instant lastUpdateDate;
#Column(name = "createUser", nullable = false, length = 30)
private String createUser;
#Column(name = "lastUpdateUser", length = 30)
private String lastUpdateUser;
#Column(name = "status")
#Enumerated(EnumType.STRING)
private Status status;
}
it's may help you
#Entity(name = "Post")
#Table(name = "post")
#TypeDef(
name = "pgsql_enum",
typeClass = PostgreSQLEnumType.class
)
public class Post {
#Id
private Long id;
private String title;
#Enumerated(EnumType.STRING)
#Column(columnDefinition = "post_status_info")
#Type( type = "pgsql_enum" )
private PostStatus status;
//Getters and setters omitted for brevity
}
for more ref...

Unable to create a JOIN using Spring Data JPA

I'm new to Spring Data and tried to solve the issue by following this post on SO and some other tutorials but without much success.
I'm trying to make a simple Join using Spring Data JPA between 2 tables.
The tables in the database are called:
* user_vehicle -> contains information about all vehicles per user since 1 user can have many vehicles
* vehicle_model which contains data about vehicle models (id, name, etc)
Current data in the database in the user_vehicle table:
ID | vehicle_id | user_id
1 | 1 | 1
2 | 2 | 1
Here is the code I've tried but can't get it to work (getters and setters are removed from the post to shorten it):
#Entity(name = "vehicle_model")
public class VehicleModel {
#Id
#Min(1)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long manufacturerId;
private String title;
private int ccm;
private int kw;
private int yearOfManufacture;
private int engineTypeId;
private boolean isActive;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "vehicle_id", insertable = false, updatable = false)
#Fetch(FetchMode.JOIN)
private UserVehicle userVehicle;
}
#Entity(name = "user_vehicle")
public class UserVehicle {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(nullable = false)
private long vehicleId;
#Column(nullable = false)
private long userId;
#OneToMany(targetEntity = VehicleModel.class, mappedBy = "userVehicle", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
List<VehicleModel> vehicleModels;
}
#Repository
public interface UserVehicleRepository extends CrudRepository<UserVehicle, Long>
{
Iterable<UserVehicle> findVehicleModelsByUserId(Long userId);
}
I'm expecting to get 2 results in the iterable with filled vehicle_model data. Instead I get 2 results but for the vehicleModels property I get "Unable to evaluate the expression Method threw 'org.hibernate.exception.SQLGrammarException' exception."
Here is the output from the console:
2019-06-23 02:04:10.988 DEBUG 5896 --- [nio-8080-exec-1] org.hibernate.SQL : select uservehicl0_.id as id1_1_, uservehicl0_.user_id as user_id2_1_, uservehicl0_.vehicle_id as vehicle_3_1_ from user_vehicle uservehicl0_ where uservehicl0_.user_id=?
2019-06-23 02:04:11.034 DEBUG 5896 --- [nio-8080-exec-1] org.hibernate.SQL : select vehiclemod0_.vehicle_id as vehicle_9_4_0_, vehiclemod0_.id as id1_4_0_, vehiclemod0_.id as id1_4_1_, vehiclemod0_.ccm as ccm2_4_1_, vehiclemod0_.engine_type_id as engine_t3_4_1_, vehiclemod0_.is_active as is_activ4_4_1_, vehiclemod0_.kw as kw5_4_1_, vehiclemod0_.manufacturer_id as manufact6_4_1_, vehiclemod0_.title as title7_4_1_, vehiclemod0_.vehicle_id as vehicle_9_4_1_, vehiclemod0_.year_of_manufacture as year_of_8_4_1_ from vehicle_model vehiclemod0_ where vehiclemod0_.vehicle_id=?
2019-06-23 02:04:11.035 WARN 5896 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1054, SQLState: 42S22
2019-06-23 02:04:11.035 ERROR 5896 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : Unknown column 'vehiclemod0_.vehicle_id' in 'field list'
2019-06-23 02:04:11.036 DEBUG 5896 --- [nio-8080-exec-1] org.hibernate.SQL : select vehiclemod0_.vehicle_id as vehicle_9_4_0_, vehiclemod0_.id as id1_4_0_, vehiclemod0_.id as id1_4_1_, vehiclemod0_.ccm as ccm2_4_1_, vehiclemod0_.engine_type_id as engine_t3_4_1_, vehiclemod0_.is_active as is_activ4_4_1_, vehiclemod0_.kw as kw5_4_1_, vehiclemod0_.manufacturer_id as manufact6_4_1_, vehiclemod0_.title as title7_4_1_, vehiclemod0_.vehicle_id as vehicle_9_4_1_, vehiclemod0_.year_of_manufacture as year_of_8_4_1_ from vehicle_model vehiclemod0_ where vehiclemod0_.vehicle_id=?
2019-06-23 02:04:11.037 WARN 5896 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1054, SQLState: 42S22
2019-06-23 02:04:11.037 ERROR 5896 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : Unknown column 'vehiclemod0_.vehicle_id' in 'field list'
2019-06-23 02:04:11.038 DEBUG 5896 --- [nio-8080-exec-1] org.hibernate.SQL : select vehiclemod0_.vehicle_id as vehicle_9_4_0_, vehiclemod0_.id as id1_4_0_, vehiclemod0_.id as id1_4_1_, vehiclemod0_.ccm as ccm2_4_1_, vehiclemod0_.engine_type_id as engine_t3_4_1_, vehiclemod0_.is_active as is_activ4_4_1_, vehiclemod0_.kw as kw5_4_1_, vehiclemod0_.manufacturer_id as manufact6_4_1_, vehiclemod0_.title as title7_4_1_, vehiclemod0_.vehicle_id as vehicle_9_4_1_, vehiclemod0_.year_of_manufacture as year_of_8_4_1_ from vehicle_model vehiclemod0_ where vehiclemod0_.vehicle_id=?
2019-06-23 02:04:11.039 WARN 5896 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1054, SQLState: 42S22
2019-06-23 02:04:11.040 ERROR 5896 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : Unknown column 'vehiclemod0_.vehicle_id' in 'field list'
2019-06-23 02:04:11.042 DEBUG 5896 --- [nio-8080-exec-1] org.hibernate.SQL : select vehiclemod0_.vehicle_id as vehicle_9_4_0_, vehiclemod0_.id as id1_4_0_, vehiclemod0_.id as id1_4_1_, vehiclemod0_.ccm as ccm2_4_1_, vehiclemod0_.engine_type_id as engine_t3_4_1_, vehiclemod0_.is_active as is_activ4_4_1_, vehiclemod0_.kw as kw5_4_1_, vehiclemod0_.manufacturer_id as manufact6_4_1_, vehiclemod0_.title as title7_4_1_, vehiclemod0_.vehicle_id as vehicle_9_4_1_, vehiclemod0_.year_of_manufacture as year_of_8_4_1_ from vehicle_model vehiclemod0_ where vehiclemod0_.vehicle_id=?
2019-06-23 02:04:11.043 WARN 5896 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1054, SQLState: 42S22
2019-06-23 02:04:11.043 ERROR 5896 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : Unknown column 'vehiclemod0_.vehicle_id' in 'field list'
2019-06-23 02:04:11.045 DEBUG 5896 --- [nio-8080-exec-1] org.hibernate.SQL : select vehiclemod0_.vehicle_id as vehicle_9_4_0_, vehiclemod0_.id as id1_4_0_, vehiclemod0_.id as id1_4_1_, vehiclemod0_.ccm as ccm2_4_1_, vehiclemod0_.engine_type_id as engine_t3_4_1_, vehiclemod0_.is_active as is_activ4_4_1_, vehiclemod0_.kw as kw5_4_1_, vehiclemod0_.manufacturer_id as manufact6_4_1_, vehiclemod0_.title as title7_4_1_, vehiclemod0_.vehicle_id as vehicle_9_4_1_, vehiclemod0_.year_of_manufacture as year_of_8_4_1_ from vehicle_model vehiclemod0_ where vehiclemod0_.vehicle_id=?
2019-06-23 02:04:11.046 WARN 5896 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1054, SQLState: 42S22
2019-06-23 02:04:11.046 ERROR 5896 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : Unknown column 'vehiclemod0_.vehicle_id' in 'field list'
2019-06-23 02:04:11.048 DEBUG 5896 --- [nio-8080-exec-1] org.hibernate.SQL : select vehiclemod0_.vehicle_id as vehicle_9_4_0_, vehiclemod0_.id as id1_4_0_, vehiclemod0_.id as id1_4_1_, vehiclemod0_.ccm as ccm2_4_1_, vehiclemod0_.engine_type_id as engine_t3_4_1_, vehiclemod0_.is_active as is_activ4_4_1_, vehiclemod0_.kw as kw5_4_1_, vehiclemod0_.manufacturer_id as manufact6_4_1_, vehiclemod0_.title as title7_4_1_, vehiclemod0_.vehicle_id as vehicle_9_4_1_, vehiclemod0_.year_of_manufacture as year_of_8_4_1_ from vehicle_model vehiclemod0_ where vehiclemod0_.vehicle_id=?
2019-06-23 02:04:11.049 WARN 5896 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1054, SQLState: 42S22
2019-06-23 02:04:11.049 ERROR 5896 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : Unknown column 'vehiclemod0_.vehicle_id' in 'field list'
Found a solution here: https://www.baeldung.com/jpa-many-to-many
I've been looking it a bit wrong since this is a ManyToMany relationship. My idea was to go to the "middle" table and select all vehicle_id where userId = :id and from the list of vehicle_ids to get details for each vehicle.
Here is the correct implementation that works:
#Entity(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String firstName;
private String lastName;
private boolean isActive;
#OneToMany(mappedBy = "user")
private Set<UserVehicle> userVehicles;
#Entity(name = "user_vehicle")
public class UserVehicle {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private boolean isActive;
#ManyToOne
#JoinColumn(name = "vehicle_id")
private Vehicle vehicle;
#ManyToOne
#JoinColumn(name = "user_id")
private User user;
#Entity(name = "vehicle_model")
public class Vehicle {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long manufacturerId;
private String title;
private int ccm;
private int kw;
private int yearOfManufacture;
private int engineTypeId;
private boolean isActive;
#OneToMany(mappedBy = "vehicle")
private Set<UserVehicle> userVehicles;
Finally, in the repository Interface I have a method like this:
public interface UserVehicleRepository extends CrudRepository<UserVehicle, Long> {
Iterable<UserVehicle> findVehicleModelsByUserId(Long userId);
The output comes out like this:
[
{
"id": 2,
"vehicle": {
"id": 2,
"manufacturerId": 1,
"title": "Fazer FZ1S",
"ccm": 998,
"kw": 110,
"yearOfManufacture": 2008,
"engineTypeId": 1,
"active": true
},
"user": {
"id": 2,
"username": "sfajkovic",
"password": "33",
"firstName": "Ivan",
"lastName": "Fajkovic",
"active": true
},
"active": true
}
]
The issue is not that I don't really want the user object in the result so now I need to figure that one out. And after that, I will try to map VehicleManufacturer class to get those results as well in the same response.
Here is the solution to do what I intentionally wanted - to search Vehicles based on the user_id in the user_vehicle table:
#Entity(name = "user_vehicle")
public class UserVehicle {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private boolean isActive;
private long userId;
#ManyToOne
#JoinColumn(name = "vehicle_id")
private Vehicle vehicle;
#Entity(name = "vehicle_model")
public class Vehicle {
#Id
#Min(1)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long manufacturerId;
private String title;
private int ccm;
private int kw;
private int yearOfManufacture;
private int engineTypeId;
private boolean isActive;
#OneToMany(mappedBy = "vehicle")
private Set<UserVehicle> userVehicles;
#Repository
public interface UserVehicleRepository extends CrudRepository<UserVehicle, Long> {
Iterable<UserVehicle> findVehicleModelsByUserId(Long userId);
The User class is actually not used at all:
#Entity(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String firstName;
private String lastName;
private boolean isActive;
This is a OneToMany relationship now and is doing what I actually wanted in the first time.
Hope it helps someone

Spring jpa spring.jpa.hibernate.ddl-auto:create ORA-02000: missing ALWAYS keyword

When I used spring-boot-starter-data-jpa and I set spring.jpa.hibernate.ddl-auto:create and my entity like this
#Entity
public class BaseOnDoubleValue extends DoubleData {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "uuid",length = 40)
private long uuid;
private int baseid;
then I got a eror like this
2015-11-19 11:07:02.438 ERROR 5876 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: create table base_on_double_value (uuid bigint generated by default as identity, baseid integer not null, date_time timestamp, error integer not null, id integer not null, quality smallint not null, base_value double, primary key (uuid))
2015-11-19 11:07:02.438 ERROR 5876 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : ORA-02000: missing ALWAYS keyword
Can you help me figure it?
I fix this problem by myself.
I add this to application.properties
spring.jpa.database= oracle

ERROR SchemaExport with Hibernate

I want to create list of embedded objects with Hibernate and MySql.
But I cought bunch of errors:
Hibernate: alter table USERS drop foreign key FK_qymdwjo8d0eu0lhfd3ngfs74d
2014-07-09 15:40:47 ERROR SchemaExport:425 - HHH000389: Unsuccessful: alter table USERS drop foreign key FK_qymdwjo8d0eu0lhfd3ngfs74d
2014-07-09 15:40:47 ERROR SchemaExport:426 - Can't DROP 'FK_qymdwjo8d0eu0lhfd3ngfs74d'; check that column/key exists
Hibernate: drop table if exists USERS
2014-07-09 15:40:48 ERROR SchemaExport:425 - HHH000389: Unsuccessful: drop table if exists USERS
2014-07-09 15:40:48 ERROR SchemaExport:426 - Cannot delete or update a parent row: a foreign key constraint fails
Hibernate: drop table if exists hibernate_unique_key
Hibernate: create table USERS (id integer not null, city varchar(35), pincode varchar(35), state varchar(35), street varchar(35), description varchar(35), joinedDate date, name varchar(35), ADDRESSES_ID bigint not null, primary key (ADDRESSES_ID))
2014-07-09 15:40:48 ERROR SchemaExport:425 - HHH000389: Unsuccessful: create table USERS (id integer not null, city varchar(35), pincode varchar(35), state varchar(35), street varchar(35), description varchar(35), joinedDate date, name varchar(35), ADDRESSES_ID bigint not null, primary key (ADDRESSES_ID))
2014-07-09 15:40:48 ERROR SchemaExport:426 - Table 'users' already exists
Hibernate: alter table USERS add constraint FK_qymdwjo8d0eu0lhfd3ngfs74d foreign key (id) references USERS (ADDRESSES_ID)
2014-07-09 15:40:48 ERROR SchemaExport:425 - HHH000389: Unsuccessful: alter table USERS add constraint FK_qymdwjo8d0eu0lhfd3ngfs74d foreign key (id) references USERS (ADDRESSES_ID)
2014-07-09 15:40:48 ERROR SchemaExport:426 - Cannot add foreign key constraint
Hibernate: create table hibernate_unique_key ( next_hi integer )
Hibernate: insert into hibernate_unique_key values ( 0 )
2014-07-09 15:40:48 INFO SchemaExport:405 - HHH000230: Schema export complete
Hibernate: insert into USERS (city, pincode, state, street, description, joinedDate, name) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: select next_hi from hibernate_unique_key for update
Hibernate: update hibernate_unique_key set next_hi = ? where next_hi = ?
Hibernate: insert into USERS (id, ADDRESSES_ID, city, pincode, state, street) values (?, ?, ?, ?, ?, ?)
2014-07-09 15:40:48 WARN SqlExceptionHelper:144 - SQL Error: 1054, SQLState: 42S22
2014-07-09 15:40:48 ERROR SqlExceptionHelper:146 - Unknown column 'ADDRESSES_ID' in 'field list'
2014-07-09 15:40:48 INFO AbstractBatchImpl:208 - HHH000010: On release of batch it still contained JDBC statements
org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:80)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:190)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:62)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1311)
at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:67)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at com.demo.hibernate.HibernateDemo.createUser(HibernateDemo.java:59)
at com.demo.hibernate.HibernateDemo.main(HibernateDemo.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'ADDRESSES_ID' in 'field list'
Here is main():
public static void main(String[] args) {
try {
HibernateDemo demo = new HibernateDemo();
UserDetails user = new UserDetails();
Address address = new Address();
address.setStreet("Name");
address.setCity("Kiev");
address.setPincode("00000");
address.setState("My state");
Address addr = new Address();
addr.setStreet("new name");
addr.setCity("Lviv");
addr.setPincode("79040");
addr.setState("state");
user.getListOfAddresses().add(address);
user.getListOfAddresses().add(addr);
user.setUserName("Carl");
user.setJoinedDate(new Date());
user.setDescription("it is cool guy");
user.setAddress(address);
demo.createUser(user);
demo.listUsers();
user.setUserName("Bruno Shults");
demo.updateUser(user);
demo.listUsers();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.runFinalizersOnExit(true);
System.exit(1);
}
UserDetails class:
#Entity
#Table(name = "USERS")
public class UserDetails {
#Id
#GeneratedValue
#Column(name = "id")
private int userId;
#Column(name = "name", length = 35)
private String userName;
#Temporal(TemporalType.DATE)
private Date joinedDate;
#Column(length = 35)
private Address address;
#Column(length = 35)
private String description;
#ElementCollection
#JoinTable(name = "USERS", joinColumns = #JoinColumn(name = "id"))
#GenericGenerator(name = "hilo-gen", strategy = "hilo")
#CollectionId(columns = {#Column(name = "ADDRESSES_ID")}, generator = "hilo-gen", type = #Type(type = "long"))
private Collection<Address> listOfAddresses = new ArrayList<Address>();
// getters and setters
Address class:
#Embeddable
public class Address {
#Column(length = 35)
private String street;
#Column(length = 35)
private String city;
#Column(length = 35)
private String state;
#Column(length = 35)
private String pincode;
// getters and setters
cfg xml file:
<hibernate-configuration>
<session-factory>
<!--Database connection settings-->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/hibernatedb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">secret</property>
<!--JDBC connection pool-->
<property name="hibernate.connection.pool_size">2</property>
<!--SQL dialect-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!--Disable the second level cache-->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCachingRegionFactory</property>
<!--Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!--Drop and recreate the database schema on startup-->
<property name="hbm2ddl.auto">create</property>
<!--<property name="hbm2ddl.auto">update</property>-->
<!-- List of XML mapping files -->
<mapping class="com.demo.dto.UserDetails"/>
Here is DB struckture looking:
and diagram:
I couldn't figure out why it creates hibernate_unique_key table? It shouldn't.
Any suggestions?
well these lines
Hibernate: create table hibernate_unique_key ( next_hi integer )
Hibernate: insert into hibernate_unique_key values ( 0 )
appear because of
#GenericGenerator(name = "hilo-gen", strategy = "hilo")
in your address
hilo: Generates a Integer, long or short type of ids. This uses a High – Low algorithm. As the name suggests, it depends upon the highest table id and then reads the possible lowest available value.
Read more about it here

Categories

Resources