postgresql + jpa + persistence.xml - postgresql

I have a problem to use PostgreSQL with JPA.
When i try to execute my app on glassfish i got this error:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: no schema has been selected to create in
Error Code: 0
Call: CREATE TABLE CABINET (ID INTEGER NOT NULL, PRIMARY KEY (ID))
Query: DataModifyQuery(sql="CREATE TABLE CABINET (ID INTEGER NOT NULL, PRIMARY KEY (ID))")
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:331)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:895)
So how can i specify the schema for JPA so it can be able to use postgresql
note: i have added the postgresql maven dependancy:
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</version>
</dependency>
Please help me; Thank you

The schema is specified with the "search_path" variable in postgres.
To solve your problem, you have 2 solutions:
Permanently add the search to the user used by your connection:
ALTER user username set search_path=yourschema ;
Add temporarly the search_path in the jdbc connection (which i find ugly)
set search_path=yourschema;

Related

how to work with extension created in postgres in spring data jpa

I am new to spring data jpa.
i have a legacy database , which i am trying to connect to via spring data jpa.
i have a certain extension created in postgres which is used for some of the columns in my tables
for e.g
CREATE EXTENSION IF NOT EXISTS citext WITH SCHEMA public;
this extension is created mostly for (case-insensitive text)
now when i try to map the tables using standard entity annotations, it gives me error, as its unable to understand this extension
The error i get is
g.springframework.boot.SpringApplication - Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: wrong column type encountered in column [domain_obj_nm] in table [attr_grp_defn]; found [citext (Types#OTHER)], but expecting [varchar(255) (Types#VARCHAR)]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1634)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1080)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
at com.sas.mkt.example.app.Application.main(Application.java:43)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: wrong column type encountered in column [domain_obj_nm] in table [attr_grp_defn]; found [citext (Types#OTHER)], but expecting [varchar(255) (Types#VARCHAR)]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:396)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:371)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:336)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1692)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1630)
... 16 common frames omitted
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: wrong column type encountered in column [domain_obj_nm] in table [attr_grp_defn]; found [citext (Types#OTHER)], but expecting [varchar(255) (Types#VARCHAR)]
i want a way via annotations to solve this issue, its ok if it is treated just as text column.
Hibernate is validating the schema on start-up as the ddl.auto property is set to validate.
You can either disable validation entirely or specify a column definition for the relevant #Columnproperty which should allow the validation to pass:
https://docs.oracle.com/javaee/5/api/javax/persistence/Column.html#columnDefinition()
#Column(columnDefinition = "citext") //or "other"?
private String myField;
Note that the column definition only affects DDL operations i.e. schema creation or validation.
Disabling validation entirely depends on your set-up. In a spring-boot app for example you set spring.jpa.hibernate.ddl-auto = false

Table not found on postresql connection from spring boot 2

I am trying to perform a basic connection between to a local postgresql DB from a very basic SpringBootProject (for training purpose).
# configure postgresql
spring.datasource.platform=postgres
spring.datasource.jdbc-url=jdbc:postgresql://localhost:5432/db
spring.datasource.username=postgres
spring.datasource.password=
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.database-platform = org.hibernate.dialect.PostgreSQL94Dialect
spring.jpa.hibernate.ddl-auto=none
So far, I have managed to have it compile and run... but when I am trying to access my DB, I get a "Table "FILMS" not found" error (org.h2.jdbc.JdbcSQLException). When I insert data from a data.sql, I get the inserted movies. But without this initializer, I cannot get data from my db...
Table "FILMS" not found; SQL statement:
select film0_.code as
code1_0_, film0_.date_prod as date_pro2_0_, film0_.did as did3_0_,
film0_.kind as kind4_0_, film0_.title as title5_0_ from films film0_
[42102-197]
2018-07-26 12:24:18.151 ERROR 10376 --- [nio-9000-exec-1]
o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for
servlet [dispatcherServlet] in context with path [] threw exception
[Request processing failed; nested exception is
org.springframework.dao.InvalidDataAccessResourceUsageException: could
not prepare statement; SQL [select film0_.code as code1_0_,
film0_.date_prod as date_pro2_0_, film0_.did as did3_0_, film0_.kind
as kind4_0_, film0_.title as title5_0_ from films film0_]; nested
exception is org.hibernate.exception.SQLGrammarException: could not
prepare statement] with root cause
org.h2.jdbc.JdbcSQLException: Table "FILMS" non trouvée
Spring boot is in version 2.03 RELEASE; both postgresql connector AND server's ones are 9.4.
I am using spring boot parent starter, as well as data-jpa-starter (with no extra hibernate/jpa depencies defined).
The source code is here
My postresql server is up, the database "db" exists, and its table public."FILMS" is full of data...
Any idea on what I am doing (or undestanding) wrong?
In your application properties file try
spring.jpa.hibernate.ddl-auto=validate
It will try to check the table in your db

When I am trying to connect to Oracle Database Through Spring Batch using Spring Datasource i am getting Error for metadata table

org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT JOB_INSTANCE_ID, JOB_NAME from BATCH_JOB_INSTANCE where JOB_NAME = ? order by JOB_INSTANCE_ID desc]; nested exception is java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist
I guess you may need to edit you xml config file
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean"
p:dataSource-ref="dataSource" p:transactionManager-ref="transactionManager"
p:tablePrefix="MYDB.BATCH_"/>
MYDB been your schema
Source

How do i create a dbo schema in the h2 sqlserver emulator?

I'm getting a
JdbcSQLException: Schema "dbo" not found;
SQL statement: create table "dbo"."TableName"
when running some boilerplate sql against the h2 sqlserver emulator (ie, with config settings:
db.default.slickdriver=com.typesafe.slick.driver.ms.SQLServerDriver
db.default.driver=net.sourceforge.jtds.jdbc.Driver
db.default.url="jdbc:h2:file:~/data/test1;MODE=MSSQLServer"
running the following:
Database.forDataSource(DB.getDataSource())
withSession {
I've tried creating the schema:
Database.forDataSource(DB.getDataSource())
withSession {
implicit session =>
Q.updateNA("CREATE SCHEMA \"dbo\" AUTHORIZATION sa;")
}
but that doesn't seem to do the trick (or report an error message). Am I missing something?
still unable to create the schema programatically. was able to easily create it via the h2 console, using the exact same query as above.
play.api.UnexpectedException: Unexpected exception[JdbcSQLException: Schema "dbo" not found; SQL statement:
create table "dbo"."TestTable" ("TestTableId" CHAR(36))
at play.core.ReloadableApplication$$anonfun$get$1$$anonfun$apply$1$$anonfun$1.apply(ApplicationProvider.scala:148) ~[play_2.10-2.2.3.jar:2.2.3]
at play.core.ReloadableApplication$$anonfun$get$1$$anonfun$apply$1$$anonfun$1.apply(ApplicationProvider.scala:112) ~[play_2.10-2.2.3.jar:2.2.3]
at scala.Option.map(Option.scala:145) ~[scala-library-2.10.4.jar:na]
at play.core.ReloadableApplication$$anonfun$get$1$$anonfun$apply$1.apply(ApplicationProvider.scala:112) ~[play_2.10-2.2.3.jar:2.2.3]
at play.core.ReloadableApplication$$anonfun$get$1$$anonfun$apply$1.apply(ApplicationProvider.scala:110) ~[play_2.10-2.2.3.jar:2.2.3]
at scala.util.Success.flatMap(Try.scala:200) ~[scala-library-2.10.4.jar:na]
Caused by: org.h2.jdbc.JdbcSQLException: Schema "dbo" not found; SQL statement:
create table "dbo"."TestTable" ("TestTableId" CHAR(36))
at org.h2.message.DbException.getJdbcSQLException(DbException.java:329) ~[h2-1.3.172.jar:1.3.172]
at org.h2.message.DbException.get(DbException.java:169) ~[h2-1.3.172.jar:1.3.172]
at org.h2.message.DbException.get(DbException.java:146) ~[h2-1.3.172.jar:1.3.172]
at org.h2.command.Parser.getSchema(Parser.java:613) ~[h2-1.3.172.jar:1.3.172]
at org.h2.command.Parser.getSchema(Parser.java:620) ~[h2-1.3.172.jar:1.3.172]
at org.h2.command.Parser.parseCreateTable(Parser.java:5254) ~[h2-1.3.172.jar:1.3.172]
Please avoid database URLs of this form (jdbc:h2:file:data/test1) as this is relative to the current working directory (and the working directory can change). Use jdbc:h2:/absolute/path instead, or jdbc:h2:~/data (relative to the current user home directory).
If you use double quotes for create table "dbo"."TableName", then you also need to use double quotes for create schema:
create schema "dbo" authorization sa

Why does EclipseLink think my database schema doesn't exist?

I'm working on a web project using EJB 3.0, and whenever EclipseLink tries to interact with the database, it says that the schema I'm using doesn't exist (which it does).
I get a massive, unhelpful stack trace from GlassFish 2.1, which begins with:
EclipseLink, version: Eclipse Persistence Services - 1.1.0.r3639-SNAPSHOT
file:/C:/Documents%20and%20Settings/nick/.personalDomain/personalDomain/applications/j2ee-apps/ScienceEar/lib/ScienceJpa-1.0-SNAPSHOT.jar-SciencePU login successful
Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 1.1.0.r3639-SNAPSHOT): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: Schema 'BEAMLINE' does not exist
Error Code: -1
Call: SELECT exp_id, fac_family, public_viewable, group_name, created_ts, status, exp_num, date_received, exp_type, title, updated_ts, text_only_title, experiment_url, proposed_eec, start_of_prep FROM beamline.eec_exp_toc
Query: ReadAllQuery(name="Experiment.findAll" referenceClass=Experiment sql="SELECT exp_id, fac_family, public_viewable, group_name, created_ts, status, exp_num, date_received, exp_type, title, updated_ts, text_only_title, experiment_url, proposed_eec, start_of_prep FROM beamline.eec_exp_toc")
I could post more of the stack trace, but it's really boring. Any ideas for why EclipseLink can't see the schema?
More info: "beamline" is the only schema I use. The SQL in the stack trace is the stuff that was generated by a NamedQuery, the first interaction with this database (and the first JPA interaction at all) in my program.
Got it - I'm connecting directly to the database, when I should be using GlassFish's connection pool.