SQLSyntaxErrorException in JPA One to many relationship - java

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 :)

Related

Unable to update null value in UUID column postrgres via jpa native query

I am trying to update with null value in uuid column in postgres db using jpa
Here is my code:
#Transactional
#Modifying
#Query(value = "update student set teacher_id=:teacherId where studentId=:studentId", nativeQuery = true)
void updateTeacherUUID(#Param("teacherId") UUID teacherId, #Param("studentId") UUID studentId);
#Data
#Entity
#NoArgsConstructor
#AllArgsConstructor
#Table(name = "student")
public class Student {
#Id
UUID studentId;
#Type(type = "org.hibernate.type.PostgresUUIDType")
#Column(name = "teacher_id", columnDefinition = "uuid")
UUID teacherId;
}
I am getting below error when I try to update
o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 42804
o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: column "teacher_id" is of type uuid but expression is of type bytea
Hint: You will need to rewrite or cast the expression.
Note: This issue occurring only in jpa native queries If I update directly using repository.update or hql its working fine
Can anyone please help me on this

Why am I obtaining this error related the auto increment PK of a PosgreSQL table using Hibernate? ERROR: relation "hibernate_sequence" does not exist

I am working on a Spring Booot application using Spring Data JPA.
As database I am using PostgreSQL and I am finding some problem mapping an auto increment primary key field of a table to the related field of my entity class.
In my database I manually created this table:
CREATE TABLE IF NOT EXISTS public."user"
(
id bigint NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 9223372036854775807 CACHE 1 ),
first_name character varying(50) COLLATE pg_catalog."default" NOT NULL,
middle_name character varying(50) COLLATE pg_catalog."default" NOT NULL,
surname character varying(50) COLLATE pg_catalog."default" NOT NULL,
CONSTRAINT user_pkey PRIMARY KEY (id)
)
Please not that the id field (my PK) is defined as a bigint with the GENERATED ALWAYS constraint and not as a serial (this because serial data type is deprecated because it is not part of the SQL standard).
Then I created this entity class mapping this table:
package com.easydefi.users.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
#Entity
#Table(name = "portal_user")
#Data
public class User implements Serializable {
private static final long serialVersionUID = 5062673109048808267L;
#Id
#Column(name = "id")
private int id;
#Column(name = "first_name")
private String firstName;
#Column(name = "middle_name")
private String middleName;
#Column(name = "surname")
private String surname;
public User(String firstName, String middleName, String surname, char sex, Date birthdate, String taxCode,
String eMail, String contactNumber, Date createdAt) {
super();
this.firstName = firstName;
this.middleName = middleName;
this.surname = surname;
}
}
Then I have this repository interface (at the moment it is empty because I am testing only the save() method directly provided by JpaRepository):
public interface UsersRepository extends JpaRepository<User, Integer> {
}
Finnally I created this simple unit test method in order to test the insert of a new record via the save() method of my repository:
#SpringBootTest()
#ContextConfiguration(classes = GetUserWsApplication.class)
#TestMethodOrder(OrderAnnotation.class)
public class UserRepositoryTest {
#Autowired
private UsersRepository userRepository;
#Test
#Order(1)
public void testInsertUser() {
User user = new User("Mario", null, "Rossi", 'M', new Date(), "XXX", "xxx#gmail.com", "329123456", new Date());
userRepository.save(user);
assertTrue(true);
}
}
the problem is that when the save() method is performed I am obtaining this exception:
Hibernate:
insert
into
portal_user
(first_name, middle_name, surname, id)
values
(?, ?, ?, ?)
2021-11-04 12:17:39.576 WARN 11436 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 428C9
2021-11-04 12:17:39.578 ERROR 11436 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: cannot insert a non-DEFAULT value into column "id"
Detail: Column "id" is an identity column defined as GENERATED ALWAYS.
Hint: Use OVERRIDING SYSTEM VALUE to override.
So I try to modify the mapping of the id field into my entity class, in this way:
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
But running my test method now the save() method execution give me this other error:
Hibernate:
select
nextval ('hibernate_sequence')
2021-11-04 12:20:21.133 WARN 11639 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 42P01
2021-11-04 12:20:21.136 ERROR 11639 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: relation "hibernate_sequence" does not exist
Position: 17
What is the problem? What am I missing? How can I try to fix this issue?
Change
GeneratedValue(strategy=GenerationType.AUTO)
To
#GeneratedValue(strategy=GenerationType.IDENTITY)
Because GenerationType.IDENTITY create primary key with auto increment that is not modified manually.
The error is definitely on this line.
id bigint NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 9223372036854775807 CACHE 1 ),
If you want a quick fix, you can change it to the one below.
SERIAL works in Postgres just fine. Sure, it might not run on other databases, but how often does an IT project do a DB migration ? Never.
id serial PRIMARY KEY NOT NULL,
Does this solve your problem ? Or you somehow need to solve it without SERIAL for some reason ?

Relation "xxxx" does not exist

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)'

Hibernate/JPA - one primary key parent to composite key child

Whats wrong in my jpa mapping, im trying to map the parent class with one primary key to the child class with composite key, but it seems its inserting in the wrong table, it already generate 2 table but unfortunately i didn't bind the foreign key(policy_value_summary_id)
#Entity
#Table(name = "POLICY_VALUE_SUMMARY")
public class PolicyValueSummary {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="POLICY_VALUE_SUMMARY_ID")
private Long policyValueSummaryId;
#MapsId("policyValueSummaryId")
#OneToMany
private Set<PolicyValue> policyValues;
}
the child class have composite keys with one is the parent id.
#Entity
#Table(name = "POLICY_VALUE")
public class PolicyValue {
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "policyValueSummaryId", column = #Column(name = "POLICY_VALUE_SUMMARY_ID")),
#AttributeOverride(name = "planAtrId", column = #Column(name = "PLAN_ATR_ID")) })
private PolicyValuePk policyValuePk;
}
This is my child class composite keys.
#Embeddable
public class PolicyValuePk implements Serializable {
private Long policyValueSummaryId;
private Long planAtrId;
}
Im trying to save the policy summary value(parent) with the policy value(child class) like this
PolicyValuePk pk = new PolicyValuePk();
pk.setPlanAtrId(Long.valueOf("1"));
Set<PolicyValue> policyValues = new HashSet<>();
policyValues.add(new PolicyValue(pk));
PolicyValueSummary summary = new PolicyValueSummary();
summary.setPolicyValues(policyValues);
repo.save(summary);
Here is the error that being output to me
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into policy_value_summary (policy_value_summary_id) values (?)
Hibernate: insert into policy_value_summary_policy_values (policy_value_summary_policy_value_summary_id, policy_values_plan_atr_id, policy_values_policy_value_summary_id) values (?, ?, ?)
WARN 6880 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 972, SQLState: 42000
ERROR 6880 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-00972: identifier is too long
No, prior to Oracle version 12.2, identifiers are not allowed to exceed 30 characters in length. See the document
http://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements008.htm#SQLRF00223
But from from version 12.2 they can be up to 128 bytes long

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