Special characters with JPA, JDBC, and mysql - jpa

I use JPA, JDBC and MySQL for my Spring Boot project. I have some trouble with special characters.
If I write an SQL query via JdbcTemplate, it's just fine. I can get back "á" characters.
But if it's via JPA, those characters are �-s.
The schema's default collation is utf8_hungarian_ci, and the default characterset is utf8.
My application.properties:
spring.jpa.database: MYSQL
spring.jpa.hibernate.ddl-auto: update
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url: jdbc:mysql://localhost:3306/databasename?useUnicode=yes&characterEncoding=UTF-8
spring.datasource.username: root
spring.datasource.password: password
I have two tables, user and userroles, and they are connected with #ManyToMany relations with a jointable.
User.java:
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(
name = "user_userrole",
joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "userrole_id", referencedColumnName = "id"))
private List<UserRole> userRoles;
public List<UserRole> getUserRoles() {
return userRoles;
}
UserRole.java:
#ManyToMany(mappedBy = "userRoles")
private List<User> users;
When I call this method:
currentUser.getUserRoles();
all "á" characters are replaced by �-s.
What am I missing?
EDIT:
I added a new user: árvíztűrő tükörfúrógép to the database. (I could do it without any problem, and I save user with jpa too, by the way.)
But when I tried to log in, I've got this exception:
error":"Internal Server Error","exception":"java.io.CharConversionException"
,"message":"Not an ISO 8859-1 character: ű"
pom.xml:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>

<property name="hibernate.connection.useUnicode" value="true" />
<property name="hibernate.connection.characterEncoding" value="UTF-8" />
with hibernate 4.3.1 this works:
<property name="connection.useUnicode">true</property>
<property name="connection.characterEncoding">utf-8</property>

Please add below in web xml
<filter>
<filter-name>SetCharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SetCharacterEncodingFilter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>

Related

JPA not generating ddl files

I'm setting up a JavaEE Webapplication and want to generate ddl files so I can see what they look like
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence"
version="2.1">
<persistence-unit name="contentAggregatorPU">
<class>contentAggregator.model.Item</class>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="javax.persistence.schema-generation.scripts.action" value="drop-and-create"/>
<property name="javax.persistence.schema-generation.scripts.create-target" value="contentAggregatorCreate.ddl"/>
<property name="javax.persistence.schema-generation.scripts.drop-target" value="contentAggregatorDrop.ddl"/>
</properties>
</persistence-unit>
</persistence>
It just does not generate the files.
Honestly I never used the mechanism. While it seems to work for my local-resource minimal JPA playground it gave me errors when attempting to deploy to wildfly. I've always used a small utility class for generating a schema.
public class SchemaTranslator {
public static void main(String[] args) throws IOException {
Class<?>[] entityClasses = {
Class1.class,
Class2.class,
};
MetadataSources metadata = new MetadataSources(new StandardServiceRegistryBuilder()
.applySetting("hibernate.hbm2ddl.auto", "create")
.applySetting("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect")
// .applySetting("hibernate.physical_naming_strategy", "package.MyImprovedNamingStrategy")
.build()
);
// [...] adding annotated classes to metadata here...
for (Class<?> clazz : entityClasses)
metadata.addAnnotatedClass(clazz);
EnumSet<TargetType> targetTypes = EnumSet.of(TargetType.STDOUT, TargetType.SCRIPT);
SchemaExport export = new SchemaExport()
// .setHaltOnError( haltOnError )
.setOutputFile("db-schema.sql")
.setDelimiter(";");
export.create(targetTypes, (MetadataImplementor) metadata.buildMetadata());
}
}

datanucleus neo4j - Unable to obtain lock on store lock file

I am developing an WebApp that uses datanucleus as JPA - Provider and Neo4j as No-SQL database.
My dependencies are
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-core</artifactId>
<version>[5.0.0-m1, 5.9)</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-api-jpa</artifactId>
<version>[5.0.0-m1, 5.9)</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>[1.2, 1.3)</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-neo4j</artifactId>
<version>[5.0.0-m1, 5.9)</version>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j</artifactId>
<version>2.3.0</version>
</dependency>
My persistence.xml looks like
<persistence-unit name="neo4j">
<provider>org.datanucleus.api.jpa.PersistenceProviderImpl</provider>
<class>entities.Person</class>
<class>entities.Car</class>
<exclude-unlisted-classes/>
<properties>
<property name="javax.persistence.jdbc.url" value="neo4j:C:\Users\phe\Documents\Neo4j\sampledatanucleus"/>
<!-- <property name="datanucleus.storeManagerType" value="neo4j"/> -->
<property name="datanucleus.storeManagerType" value="neo4j"/>
</properties>
</persistence-unit>
I am persisting the entities like this
Person person = new Person(personName, personAge);
Car car = new Car(carName);
car.setOwner(person);
person.getCars().add(car);
em.persist(person);
When persisting the entities I get an exception:
Caused by: org.neo4j.kernel.StoreLockException: Unable to obtain lock on store lock file: C:\Users\phe\Documents\Neo4j\sampledatanucleus\store_lock. Please ensure no other process is using this database, and that the directory is writable (required even for read-only access)
at org.neo4j.kernel.StoreLocker.storeLockException(StoreLocker.java:93)
at org.neo4j.kernel.StoreLocker.checkLock(StoreLocker.java:85)
at org.neo4j.kernel.StoreLockerLifecycleAdapter.start(StoreLockerLifecycleAdapter.java:44)
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:528)
... 153 more
This makes me crazy. The directory I defined in the perstistence.xml is empty when I start the applictaion. Therefore it is impossible that it is locked by another process. DataNucleus then creates the database. I can access it with Neo4j Browser. But Persisting does not work.
Any ideas?
EDIT:
This is the class I use for querying
#Stateless
public class Manager {
#PersistenceContext(unitName = "neo4j")
private EntityManager em;
public List<Person> queryCache() {
String statement = "Select o from Person o";
Query query = em.createQuery(statement, Person.class);
List<Person> list = query.getResultList();
em.close();
return list;
}
public void save(String personName, Double personAge, String carName) {
Person person = new Person(personName, personAge);
Car car = new Car(carName);
car.setOwner(person);
person.getCars().add(car);
em.persist(person);
}
}
These two methods get called by the controller when clicking the corresponding buttons on the view.

Persistence unit for class issue

I am using Kundera with mongodb on a windows 7 box. I am trying to use int data type. But I am getting the following error.
Exception in thread "main" com.impetus.kundera.configure.schema.SchemaGenerationException: Persistence unit for class : int is not loaded
at com.impetus.kundera.configure.SchemaConfiguration.parseRelations(SchemaConfiguration.java:262)
at com.impetus.kundera.configure.SchemaConfiguration.configure(SchemaConfiguration.java:151)
at com.impetus.kundera.configure.ClientMetadataBuilder.buildClientFactoryMetadata(ClientMetadataBuilder.java:48)
at com.impetus.kundera.persistence.EntityManagerFactoryImpl.configureClientFactories(EntityManagerFactoryImpl.java:404)
at com.impetus.kundera.persistence.EntityManagerFactoryImpl.configure(EntityManagerFactoryImpl.java:157)
at com.impetus.kundera.persistence.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:131)
at com.impetus.kundera.KunderaPersistence.createEntityManagerFactory(KunderaPersistence.java:85)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown Source)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown Source)
at com.atomconnect.App.insertIntoMongo(App.java:37)
at com.atomconnect.App.main(App.java:53)
My entity object has the following fields
#Id
#Column(name="MESSAGE_ID")
private String messageId;
#Column(name = "SUBJECT")
private String subject;
#Column(name = "BODY")
private String body;
#Column(name = "zipcode")
private int zipcode;
#Embedded
private Contact from;
My persistence.xml looks like below
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="2.0">
<persistence-unit name="ac">
<provider>com.impetus.kundera.KunderaPersistence</provider>
<properties>
<property name="kundera.nodes" value="localhost" />
<property name="kundera.port" value="12345" />
<property name="kundera.keyspace" value="test" />
<property name="kundera.dialect" value="mongodb" />
<property name="kundera.client.lookup.class" value="com.impetus.client.mongodb.MongoDBClientFactory" />
<property name="" value="datastore_mongo.jar"/>
<!-- <property name="kundera.cache.provider.class" value="com.impetus.kundera.cache.ehcache.EhCacheProvider" />
<property name="kundera.cache.config.resource" value="/ehcache-test.xml" /> -->
</properties>
<jar-file>target/test.jar</jar-file>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>
</persistence>
I wasted 2 days around this but not able to get the solution. Any help would be appreciated
Can you try removing
property name="" value="datastore_mongo.jar"
and share test.jar entities code ? Also , which version of Kundera are you using ?
I had a class for which I have declared the one to one mapping annotation for a int data type which was never used.
This should not cause any problem but the way kundera populates metadata via reflection is the issue.

WEB9031 - cannot store entity with sequence generated id

I am using glassfish, postgres and openjpa.
I only have one bean and first want to create a new intance and store it in DB. I created a new User-Object, filled it (except the id) and got - trying to persist - following exception:
Caused by: java.lang.IllegalStateException: WEB9031: WebappClassLoader unable to load resource [org.apache.openjpa.util.LongId], because it has not yet been started, or was already stopped
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1401)
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1359)
at org.myPlace.server.user.UserPDO.pcNewObjectIdInstance(UserPDO.java)
at org.apache.openjpa.enhance.PCRegistry.newObjectId(PCRegistry.java:142)
at org.apache.openjpa.meta.MetaDataRepository.processRegisteredClass(MetaDataRepository.java:1694)
at org.apache.openjpa.meta.MetaDataRepository.processRegisteredClasses(MetaDataRepository.java:1644)
... 128 more
WARNING: StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() for
servlet Faces Servlet threw exception
java.lang.IllegalStateException: WEB9031: WebappClassLoader unable to load resource
[org.apache.openjpa.util.LongId], because it has not yet been started, or was already stopped
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1401)
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1359)
at org.myPlace.server.user.UserPDO.pcNewObjectIdInstance(UserPDO.java)
at org.apache.openjpa.enhance.PCRegistry.newObjectId(PCRegistry.java:142)
at org.apache.openjpa.meta.MetaDataRepository.processRegisteredClass(MetaDataRepository.java:1694)
My bean looks like this:
#Entity
#Table(name="tbl_User")
public class UserPDO implements Serializable {
private long id;
private String username;
private String password;
public UserPDO() {}
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="user_seq_gen")
#SequenceGenerator(name="user_seq_gen", sequenceName="user_seq")
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
... }
My persistence.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="myPlace" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<class>org.myPlace.server.user.UserPDO</class>
<properties>
<property name="openjpa.jdbc.DBDictionary" value="postgres"/>
<property name="openjpa.ConnectionDriverName" value="org.postgresql.Driver"/>
<property name="openjpa.ConnectionURL" value="jdbc:postgresql://localhost:5432/myPlace"/>
<property name="openjpa.ConnectionPassword" value="myPlace"/>
<property name="openjpa.ConnectionUserName" value="myPlace"/>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema"/>
<property name="openjpa.Log" value="File=/home/username/apache.log, DefaultLevel=ERROR, Tool=INFO, SQL=TRACE"/>
<property name="openjpa.DynamicEnhancementAgent" value="false" />
<property name="openjpa.RuntimeUnenhancedClasses" value="unsupported" />
<property name="openjpa.DataCache" value="false"/>
<property name="openjpa.QueryCache" value="false"/>
</properties>
</persistence-unit>
The table is created correctly, so is the sequence. But when I want to create a new user object via
public <T> T create(T t) {
this.em.persist(t);
this.em.flush();
this.em.refresh(t);
return t;
}
I get the exception mentioned above. I found some questions/answers here that suggest that deactiving runtime-enhancement should do the trick. But it didn't work for me. My first idea was, that it might be a Classloader-Leak. I copied postgres-driver and openjpa-jars into the glassfish/lib-folder.
Can anybody help? Thanks!

Spring Security Web App: different login, same authentication object

i use spring security to organize the security and user management in my GWT application. If i login as "admin", logout, and login as another user the "SecurityContextHolder.getContext()" still returns me the "admin" authentication though i use the standard spring security logout URL (/j_spring_security_logout) and after logout have to login again to access the page... somebody has a hint? I'm at the end of my knowledge =/
filters in my web.xml:
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
applicationcontext.xml:
<bean class="service.security.DefaultPermissionEvaluator" id="permissionEvaluator"/>
<bean class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler" id="expressionHandler">
<property name="permissionEvaluator" ref="permissionEvaluator"/>
</bean>
<sec:global-method-security pre-post-annotations="enabled">
<sec:expression-handler ref="expressionHandler"/>
</sec:global-method-security>
<bean class="service.security.DefaultAuthenticationProvider" id="authenticationProvider"/>
<bean class="service.security.DefaultUserDetailsManager" id="userDetailsManager"/>
<bean class="service.security.DefaultAuthenticationListener" id="customAuthListener"/>
<sec:authentication-manager>
<sec:authentication-provider ref="authenticationProvider">
</sec:authentication-provider>
</sec:authentication-manager>
<sec:http auto-config="true" use-expressions="true">
<sec:form-login default-target-url="/Index.html" always-use-default-target="true"/>
<sec:logout invalidate-session="true" logout-success-url="/" logout-url="/j_spring_security_logout"/>
<sec:intercept-url pattern="/service/admin/**" access="hasRole('ADMIN')"/>
<sec:intercept-url pattern="/**" access="hasRole('USER')"/>
</sec:http>
The problem was i did this:
class ServiceExample extends HttpServlet {
private final Authentication auth;
public ServiceExample() {
this.auth = SecurityContextHolder.getContext().getAuthentication()
}
public User getCurrentUser() {
return (User) this.auth.getPrincipal();
}
}
instead of:
class ServiceExample extends HttpServlet {
public ServiceExample() {
}
public User getCurrentUser() {
return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
}
Which makes the SecurityContext initialize once when somebody logs in (Jetty behavior) and not changing when somebody else logs in cause of jetty using the same instance...