Hibernate LocalDateTime: Postgresql schema generation creates columns of type "bytea" in external Tomcat - postgresql

Im having a problem with hibernate schema generation of my postgresql databse for my webapp which is hosted in a external tomcat (8.5.20).
For this i have set the spring.jpa.hibernate.ddl-auto to create-drop in my spring boot app.
When im running the app inside my eclipse with the embedded tomcat all LocalDateTime columns are generated as
timestamp without time zone which is fine.
But when generating the the war file and deploying to a external tomcat with activated schema generation all these columns are generated as type
bytea.
I was trying to define global jndi resources (server.xml) linked in context.xml, only context.xml based jndi reosurces and with the spring.data and spring.jpa configuration im having when running in eclipse in my application.properties. But as soon as i deploy the generated war to my external tomcat these columns are generated as bytea.
I also put the postgresql-42.1.1.jar to the tomcat lib folder but also without any success.
These are my settings for my local environemt which work fine:
spring.datasource.url= jdbc:postgresql://localhost:5432/test
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext
spring.jpa.hibernate.use-new-id-generator-mappings=true
spring.jpa.hibernate.ddl-auto=create-drop
This is a example of defining the tomcat jndi datasource in context.xml which generates the bytea columns:
<Resource name="jdbc/test" auth="Container"
type="javax.sql.DataSource" maxActive="20" maxIdle="5" maxWait="10000"
username="postgres" password="postgres" driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://localhost:5432/test">
</Resource>
In this case my application properties looks like this:
spring.datasource.jndi-name=java:comp/env/jdbc/test
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext
spring.jpa.hibernate.use-new-id-generator-mappings=true
spring.jpa.hibernate.ddl-auto=create-drop
Last i tried is to build and run a generated jar. Columns are again generated of type 'bytea'. So the only variant where the columns are generated as timezones is running the app inside eclipse...
Anybody an idea?

In general should NOT work. And yes, BLOB convention is used.
Java8 LocalDateTime isn't officially part of JPA 2.1
Question is WHY one config positive work? I'm almost sure, PostgreSQL has nothing t problem.
Maybe You have newer / older hibernate version? Newer Hibernate versions maybe have 'early release' ? Pure presumption, I'm in latest years Eclipselink user, and Eclipselink does NOT implement.
Generally suggested and good proven way is JPA type converter
#Converter(autoApply = true)
public class LocalDateAttributeConverter implements AttributeConverter<LocalDate, Date> {
#Override
public Date convertToDatabaseColumn(LocalDate locDate) {
return (locDate == null ? null : Date.valueOf(locDate));
}
#Override
public LocalDate convertToEntityAttribute(Date sqlDate) {
return (sqlDate == null ? null : sqlDate.toLocalDate());
}
}
EDIT: maybe You have such converter in some JAR, so automatically is forced???
EDIT2: maybe better code and theory by Adam Bien?
http://www.adam-bien.com/roller/abien/entry/new_java_8_date_and

Related

Spring Boot + OSGI : NoClassDefFoundError on jackson databind

I fail to configure a project based on Spring Boot, extended with OSGI, and using Jackson in a bundle
by using import/export package system (I would like to avoid to embed the lib).
I started from this project.
Maven modules:
a Spring Boot module, the main app, initialized with Felix, like the referenced project above
a bundle module, where I want to use ObjectMapper on activation like this
#Activate
public void activate() {
ObjectMapper objectMapper = new ObjectMapper();
}
But on activation I got the following error:
NoClassDefFoundError: com/fasterxml/jackson/databind/ObjectMapper
Yet, I had exported this package from the main app bundle (Spring Boot) and imported it in the bundle module.
This bundle module use maven-bundle-plugin (while the main app use nothing specific):
<instructions>
<_dsannotations>*</_dsannotations>
<_metatypeannotations>*</_metatypeannotations>
<Bundle-Vendor>Foo</Bundle-Vendor>
<Bundle-Version>${project.version}</Bundle-Version>
<Export-Service>
com.foo.bar.plugin.RestTaskPlugin
</Export-Service>
<Export-Package>
com.foo.bar.plugin.rest,
com.foo.bar.plugin.rest.web,
com.foo.bar.plugin.rest.config
</Export-Package>
<Import-Package>*;resolution:=optional</Import-Package>
<Embed-Dependency>*;scope=compile|runtime; type=!pom; inline=true</Embed-Dependency>
<Embed-Transitive>false</Embed-Transitive>
</instructions>
I only embed logback-classic and logback-core in this bundle (this could be another story...). In other words, I only have these 2 dependencies declared in the module. I also tried to add databind in provided scope but it changes nothing.
I don't get it since I have exported all "com.fasterxml.jackson" packages and sub-packages. To do so, the Spring boot initialize the Felix framework with a custom configuration, with the config key org.osgi.framework.system.packages.extra containing all packages to export automatically according to
the documention.
When I log them we can see around 100 exported packages including these ones :
....
com.fasterxml.jackson.databind.deser.impl,
com.fasterxml.jackson.databind,
com.fasterxml.jackson.core.sym,
....
The module bundle using databind MANIFEST.MF :
Export-Package: com.foooooooo.baaaar.plugin.rest;uses:="com.foooooooo.d
atagen.api.plugins,com.foooooooo.baaaaar.api.plugins.properties,com.baa
aaaaar.datagen.api.plugins.web,com.foooooooo.baaaaar.plugin.rest.config
,com.foooooooo.baaaaar.plugin.rest.web,com.foooooooo.baaaaar.task,com.d
atanumia.baaaaar.task.config,com.foooooooo.baaaaar.task.environment,com
.foooooooo.baaaaar.task.template,org.springframework.http,org.springfra
mework.web.client";version="0.1.0.SNAPSHOT",com.foooooooo.baaaaar.plugi
n.rest.web;uses:="com.foooooooo.baaaaar.api.plugins,com.foooooooo.baaaa
ar.api.plugins.web";version="0.1.0.SNAPSHOT",com.foooooooo.baaaaar.plug
in.rest.config;uses:="com.foooooooo.baaaaar.task.config,com.fasterxml.j
ackson.annotation,com.fasterxml.jackson.databind.annotation,org.springf
ramework.http";version="0.1.0.SNAPSHOT"
Export-Service: com.foooooooo.baaaaar.plugin.RestTaskPlugin
Import-Package: com.foooooooo.baaaar.api.plugins;resolution:=optional,c
om.foooooooo.baaaaar.api.plugins.properties;resolution:=optional,com.da
tanumia.baaaaar.api.plugins.web;resolution:=optional,com.foooooooo.baaa
aar.task;resolution:=optional,com.foooooooo.baaaaar.task.config;resolut
ion:=optional,com.foooooooo.baaaaar.task.environment;resolution:=option
al,com.foooooooo.baaaaar.task.template;resolution:=optional,com.foooooo
al,com.foooooooo.baaaaar.task.template;resolution:=optional,com.foooooo
oo.baaaaar.tools.file;resolution:=optional,com.fasterxml.jackson.annota
tion;resolution:=optional;version="[2.13,3)",com.fasterxml.jackson.data
bind;resolution:=optional;version="[2.13,3)",com.fasterxml.jackson.data
bind.annotation;resolution:=optional;version="[2.13,3)",com.jayway.json
path;resolution:=optional;version="[2.7,3)",java.io;resolution:=optiona
l,java.lang;resolution:=optional,java.lang.annotation;resolution:=optio
nal,java.lang.invoke;resolution:=optional,java.lang.management;resoluti
on:=optional,java.lang.reflect;resolution:=optional,java.net;resolution
:=optional,java.nio.channels;resolution:=optional,java.nio.charset;reso
lution:=optional,java.nio.file;resolution:=optional,java.security;resol
ution:=optional,java.security.cert;resolution:=optional,java.text;resol
ution:=optional,java.util;resolution:=optional,java.util.concurrent;res
olution:=optional,java.util.concurrent.atomic;resolution:=optional,java
.util.concurrent.locks;resolution:=optional,java.util.function;resoluti
on:=optional,java.util.logging;resolution:=optional,java.util.regex;res
olution:=optional,java.util.stream;resolution:=optional,java.util.zip;r
esolution:=optional,javax.mail;resolution:=optional,javax.mail.internet
;resolution:=optional,javax.management;resolution:=optional,javax.namin
g;resolution:=optional,javax.net;resolution:=optional,javax.net.ssl;res
olution:=optional,javax.servlet;resolution:=optional,javax.servlet.http
;resolution:=optional,javax.xml.namespace;resolution:=optional,javax.xm
l.parsers;resolution:=optional,javax.xml.stream;resolution:=optional,ja
vax.xml.stream.events;resolution:=optional,lombok;resolution:=optional,
org.apache.commons.lang3;resolution:=optional;version="[3.12,4)",org.co
dehaus.commons.compiler;resolution:=optional,org.codehaus.janino;resolu
tion:=optional,org.springframework.http;resolution:=optional,org.spring
framework.http.converter.json;resolution:=optional,org.springframework.
util;resolution:=optional,org.springframework.web.client;resolution:=op
tional,org.springframework.web.util;resolution:=optional,org.xml.sax;re
solution:=optional,org.xml.sax.helpers;resolution:=optional,sun.reflect
;resolution:=optional
It is difficult to see but we have the expected import-package:
com.fasterxml.jackson.databind;resolution:=optional;version="[2.13,3)"
I do not have any other loaded bundle excepted the framework bundles:
org.apache.felix.fileinstall-3.7.4.jar
org.apache.felix.scr-2.2.0.jar
org.osgi.service.cm-1.6.1.jar
org.osgi.util.function-1.2.0.jar
org.osgi.util.promise-1.2.0.jar
I spend days to understand what is happening but each new tests bring me new unresolved challenges.
I can have a working project if I change strategy and embed everything, but then in some particular situations I have a linkage problem since I use the same lib in different class loaders.
How to use import/export package system correctly ?
Any idea about the problem here ?
UPDATE: the export-import seems to work with other packages. For example I can use spring-web in provided scope, it is not in the final bundle module, and I can use some methods of spring-web, exported from main app. The problem seems to be the Jackson Databind or something in related to it.
UPDATE
If I use bnd-maven-plugin I do not have the problem, I will post it unless someone give a better answer.

Instanciate a JPA EntityManager in an Eclipse RCP (Java SE) environment

Context :
Eclipse RCP project, divided into plugins, each one devoted to a task (eg : HMI management, communications, ...)
Necessity to persist some data in a database
- ORM : hibernate's JPA (JPA 2.1, Hibernate 5.2.1 used throught an org.hibernate.core plugin as constructed [here (page 8)][1]
- database : in mysql
- constraint : Java SE environment, so the only way to obtain an EntityManager (for the persistence operations) is to create it through an EntityManagerFactory
First step (that works!) :
Plugin that manages the database operations, its structure :
com.plugin.name
JRE System Library
Plug-in Dependencies
Referenced Libraries (contains the mysql connector jar)
src/
com.plugin.name (package containing the plugin activator)
com.plugin.name.entities (package containing all my entities)
com.plugin.name.utils (package containing my access functions and a main)
META-INF/
persistence.xml
META-INF/
MANIFEST.MF
In com.plugin.name.utils I have my classes performing all the persistence functions.
In these classes, I create an EntityManagerFactory this way :
private static final EntityManagerFactory ENTITY_MANAGER_FACTORY = Persistence.createEntityManagerFactory("com.plugin.name");
where "com.plugin.name" is the persistence unit name defined in my persistence.xml
In one of those classes, I have a main running some database-related functions.
When I run this main as java application, everything works fine.
(to prevent future questions : my persistence.xml file was originally generated in the MANIFEST.MF META-INF folder but when running this main, it couldn't be found, so I moved it. I checked both configurations when calling the persistence functions from another plugin)
The problem :
I need to access my persistence functions from another plugin, let's call him com.plugin.other
So I added com.plugin.name as a dependency of this plugin.
But when I try to run the application, I get the following error :
javax.persistence.PersistenceException: No Persistence provider for EntityManager named com.plugin.name
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:61)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
When i run the main as standalone application, if there's any problem with the persistence.xml file (not found, incomplete, etc) it gets at least mentionned... Here I'm really stuck with no clue to understand where the problem comes from.
I finally made it without the persistence.xml by using the createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) method in the PersistenceProvider.
Code :
Activator a = Activator.getDefault();
Bundle b = a.getBundle();
URL url = b.getResource("META-INF/persistence.xml");
List<PersistenceProvider> providers = PersistenceProviderResolverHolder.getPersistenceProviderResolver().getPersistenceProviders();
for (PersistenceProvider pp : providers) {
PersistenceUnitInfoImpl pui = new PersistenceUnitInfoImpl();
pui.setPersistenceUnitName("persistenceUnitName");
pui.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL);
pui.setPersistenceUnitRootUrl(url);
Properties prop = pui.getProperties();
if (prop == null) {
prop = new Properties();
}
prop.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://ip:port/dbName");
prop.setProperty("javax.persistence.jdbc.user", "dbUser");
prop.setProperty("javax.persistence.jdbc.password", "dbPass");
prop.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
pui.setProperties(prop);
pui.setClassLoader(com.mysql.jdbc.Driver.class.getClassLoader());
emFactory = pp.createContainerEntityManagerFactory(pui, null);
}
}

H2 driver not found when try to connect

I have gone through some other answers, but cannot get the solution to my problem.
I am using NetBeans 7.0.1 and the latest version of the H2 DB on Win7.
I successfully use the H2 console tool and I have also added the driver in NetBeans and am able to connect (i.e. see the DB, tables, issue commands, etc). However from within my Java code when running it, I get the message: "java.lang.ClassNotFoundException:org.h2.Driver".
My code is:
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/testDB", "sa", "");
Statement query = null;
query = conn.createStatement();
String firstString = "INSERT INTO ......";
query.executeUpdate(firstString);
I have also added the H2 jar file in the classpath (although I had to create the classpath myself and point to the jar file) - I went to environment variables -> user variables
name=classpath value=.;C:\NetBeansProjects\testdemo\src\testdemo\DB\h2-1.3.165.jar
What am I doing wrong?
Add the H2 jar file in the "Libraries" section under the source code packages.
Change parent version
spring-boot-starter-parent
1.4.3.RELEASE

IllegalAccessError throwing in linux ( suse 10)

enter code herewe are using c3p0 jar for databse pooling. Now from c3p0 code, the following exception is comming
Caused by: java.lang.IllegalAccessError: tried to access class com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource$1 from class com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource
at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.setUpPropertyEvents(AbstractPoolBackedDataSource.java:74)
at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.(AbstractPoolBackedDataSource.java:63)
at com.mchange.v2.c3p0.ComboPooledDataSource.(ComboPooledDataSource.java:109)
at com.mchange.v2.c3p0.ComboPooledDataSource.(ComboPooledDataSource.java:105)
Now in AbstractPoolBackedDataSource.java (line 74)
PropertyChangeListener l = new PropertyChangeListener()
PropertyChangeListener l = new PropertyChangeListener()
{
public void propertyChange( PropertyChangeEvent evt )
{ resetPoolManager(); }
};
So, PropertyChangeListener is the inner class here .. AbstractPoolBackedDataSource$1
PropertyChangeListener is a java class java.beans.PropertyChangeListener !!
What can be the reason ? This is only happening in linux(suse 10). In Windows it is working fine(jdk 1.6_10 and jre 1.6_20). I have tried with different jdk,jre combinations ( jdk 1.6_25 etc )
I have resolved the problem using some trial and error.
Also I found, this is not os dependable as I have suspected earlier. This is easily reproducible and looks like an potential class loading bug.( though I am not sure whether it is in equinox implementation or in java !!).
Before explaining the solution, let me describe the scenario more elaborately.
We have our code deployed in a osgi(equinox) framework. There are two bundles which uses the c3p0 jar for database pooling and one of them exports the c3p0 packages. This bundle starts before the other one.
Now, according to osgi specification, osgi class loader should maintain separate class loader instances for separate bundles. Now when the second bundle tries to load classes from the c3p0 jar, its class-loader may find (from parent delegation) that the classes are already loaded !! But they are loaded from different context, which is causing the access violation.
This is initial findings, I will try to debug with the eclipse code and may be dig more into it. After changing the bundle start order, this is resolved.

Error creating Envers's EntityManagerFactory when annotations are present

Envers looks easy. Just add some hibernate properties in your persistence.xml (eventlisteners), and annotate the entities you want to audit.
I am testing this on an application using Hibernate. Here is some pom info:
org.hibernate.hibernate-entitymanager:3.4.0.GA
org.hibernate.hibernate-annotations:3.4.0.GA
org.hibernate.hibernate:3.2.6.GA
org.jboss.envers.jboss-envers:1.2.1.GA-hibernate-3.3
If I insert no annotations, my app context is loaded fine. But if I insert one, I am unable to build EntityManagerFactory.
(...)
Caused by: java.lang.NullPointerException
at org.hibernate.envers.configuration.metadata.AuditMetadataGenerator.generateInheritanceMappingData(AuditMetadataGenerator.java:305)
at org.hibernate.envers.configuration.metadata.AuditMetadataGenerator.generateFirstPass(AuditMetadataGenerator.java:353)
at org.hibernate.envers.configuration.EntitiesConfigurator.configure(EntitiesConfigurator.java:87)
at org.hibernate.envers.configuration.AuditConfiguration.(AuditConfiguration.java:86)
at org.hibernate.envers.configuration.AuditConfiguration.getFor(AuditConfiguration.java:99)
at org.hibernate.envers.event.AuditEventListener.initialize(AuditEventListener.java:260)
at org.hibernate.event.EventListeners$1.processListener(EventListeners.java:198)
at org.hibernate.event.EventListeners.processListeners(EventListeners.java:181)
at org.hibernate.event.EventListeners.initializeListeners(EventListeners.java:194)
Any help would be appreciated.
org.jboss.envers.jboss-envers:1.2.1.GA-hibernate-3.3 works with hibernate-3.3
did you try to use newer version?