Error with persistence using EclipseLink and UCanAccess - java

I am trying to develop an app for exercise reasons. I am using MSAccess 2010 as the database with UCanAccess (3.06) as the driver and the EclipseLink 2.1 as the entity framework.
I am stuck in adding new records to the database. Here the error code:
Internal Exception: net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::3.0.6 user lacks privilege or object not found: IDENTITY_VAL_LOCAL
Error Code: -5501
Call: SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1
Query: ValueReadQuery(name="SEQ_GEN_IDENTITY" sql="SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1")
It seems to me that the autogenerate of the id fails. The entity class was generated vie Netbeans and looks like this:
#Transient
private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "ID")
private Integer id;

By default, EclipseLink tries to automatically detect the underlying database and generate SQL statements using the appropriate SQL dialect. That apparently isn't working for you because the SQL statement to retrieve the last created identity value is not recognized by UCanAccess .
You could try adding a target-database directive to your EclipseLink configuration specifying SQLServer in an attempt to get a working SQL statement (SELECT ##IDENTITY) to retrieve the last created ID value. However, bear in mind that there are significant differences between T-SQL and Access SQL so you will probably continue to encounter other compatibility issues between EclipseLink and UCanAccess.

before knowing above answer i was also facing same problem for inserting new record in access Database ,
Thanks to Mr. Gord Thompson to give a great Solution for me ,
and it is working too.
i have just added one line in my persistence.xml file..
property name="eclipselink.target-database" value="HSQL"
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="OnePU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>design_frames.One</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:ucanaccess://C:\One\One.accdb"/>
<property name="javax.persistence.jdbc.user" value=""/>
<property name="javax.persistence.jdbc.driver" value="net.ucanaccess.jdbc.UcanaccessDriver"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="eclipselink.target-database" value="HSQL"/>
</properties>
</persistence-unit>
</persistence>

Related

How to add missing columns in a multi-schema based multi-tenant web app using eclipselink

I'm developing a multi-tenant web app with "Shared Database/Separate Schemas" approach using java, jpa(eclipselink), mysql. My persistence file looks like:
<persistence-unit name="GroupBuilderPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.cache.shared.default" value="false"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/?"/>
<property name="eclipselink.ddl-generation" value="create-or-extend-tables"/>
<--- Here goes other properties definition -->
</persistence-unit>
Now here is my EntityMangerFactory and EntityManager:
emfForTenant = Persistence.createEntityManagerFactory("GroupBuilderPU");
EntityManager em = emfForTenant.createEntityManager();
em.setProperty("eclipselink.tenant-id", schemaNameAsTenantId);
Its working fine untill I'm adding any new persistence column in any entity.
Like I've a Entity UserAccount where I've added a new column 'String rentalinfo' :
#Entity
#Multitenant(MultitenantType.TABLE_PER_TENANT)
#TenantTableDiscriminator(type = TenantTableDiscriminatorType.SCHEMA, contextProperty = PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT)
public class UserAccount implements Serializable {
...
private String rentalinfo;//Newly added column
...
}
Now after that this the following line is giving error:
em.createQuery("SELECT ua FROM UserAccount ua").getResultList();
The error is:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'RENTALINFO' in 'field list'
So what will be the solution for adding new column (extend table) in this approach?
You are getting this exception because the 'RENTALINFO' column does not exist on your UserAccount table. Under normal circumstances, setting "create-or-extend-tables" will have EclipseLink issue an ALTER to your existing table, adding the new column. However, it would appear ddl generation is not supported for MultitenantType.TABLE_PER_TENANT: https://wiki.eclipse.org/EclipseLink/DesignDocs/Multi-Tenancy/TablePerTenant
Not supported:
Schema generation will not be supported since it requires knowledge of all the tenants (schema's) and further to that, access provision must be set once the tables are created if using schema level table per tenant.
So there is no ALTER and your table does not have the column.
As a side note, you can turn on EclipseLink SQL logging using the following persistence properties:
<properties>
<property name="eclipselink.logging.level" value="ALL"/>
<property name="eclipselink.logging.level.sql" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
</properties>
This way, you can see what queries EclipseLink is (or in this case, isn't) executing.

Hibernate with Sql Server fail for nvarchar field with "No Dialect mapping..."

I'm using Hibernate's JPA-Implementation to access our SQL Server 2012 database.
When trying to select a nvarchar field in a native query, I get an exception "No Dialect mapping for JDBC type: -9".
It looks much like No Dialect mapping for JDBC type: -9 with Hibernate 4 and SQL Server 2012 or No Dialect mapping for JDBC type: -9 but I couldn't find a solution for me there (both are not using JPA).
My database setup:
CREATE TABLE NvarcharExample(
exampleField nvarchar(20) PRIMARY KEY
)
INSERT INTO NvarcharExample(exampleField) VALUES ('hello')
My code:
import java.io.IOException;
import javax.persistence.*;
#Entity
class NvarcharExample {
#Id
public String exampleField;
}
public class NvarcharTest {
public static void main(String[] args) throws IOException, InterruptedException {
String queryString = "SELECT e.exampleField FROM NvarcharExample e";
// establish connection
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("persistenceUnit");
try {
EntityManager entityManager = entityManagerFactory.createEntityManager();
// access data using JPQL
entityManager.createQuery(queryString).getResultList(); // works
// access data using SQL (native query)
entityManager.createNativeQuery(queryString).getResultList(); // fails
} finally {
entityManagerFactory.close();
}
}
}
My persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="persistenceUnit">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<!-- database connection settings -->
<property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://<servername>:<port>;databaseName=<databasename>" />
<property name="javax.persistence.jdbc.user" value="<user>" />
<property name="javax.persistence.jdbc.password" value="<password>" />
</properties>
</persistence-unit>
</persistence>
With sql logging enable, I get this output in my console
select nvarcharex0_.exampleField as col_0_0_ from NvarcharExample nvarcharex0_
SELECT e.exampleField FROM NvarcharExample e
I'm using
hibernate-core-4.3.10.Final.jar
hibernate-entitymanager-4.3.10.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
hibernate-commons-annotations-4.0.5.Final.jar
sqljdbc41.jar
What I've tried:
using a varchar instead of nvarchar makes it work, but I need nvarchar
using jpql instead of sql works (see my example code), but I need a native query
I tried sqljdbc4.jar in Version 4.0 and 4.1 and I tried sqljdbc41.jar
I head about subclassing the SQL Server Dialect class, but did not have any success with that
I added <property name="dialect" value="org.hibernate.dialect.SQLServerDialect" /> to my persistence.xml (right behind the password property)
I added <property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect" /> to my persistence.xml
I changed the persistence provider to <provider>org.hibernate.ejb.HibernatePersistence</provider>
Using #Nationalized attribute helped me to map String to nvarchar for MS SQL 2012 without dialect subclassing.
At the same time setting the hibernate.use_nationalized_character_data property to true did not worked for me.
For futher information watch docs National Character Types.
I was able to resolve that issue by subclassing the SQLServerDialect:
package packagename;
import java.sql.Types;
public class SqlServerDialectWithNvarchar extends org.hibernate.dialect.SQLServerDialect {
public SqlServerDialectWithNvarchar() {
registerHibernateType(Types.NVARCHAR, 4000, "string");
}
}
and referencing it in my persistence.xml:
<property name="hibernate.dialect" value="packagename.SqlServerDialectWithNvarchar" />
PS: It seems to be fixed with hibernate 5.1 according to this ticket: https://hibernate.atlassian.net/browse/HHH-10183

How entity manager read new record inserted by others

My application use JPA/hibernate to read data from database. The application is read only, and data is inserted by other program.
The problem is that my application can only read flesh data in the first time. When new data is inserted by other program, my application cannot see it.
Here is my test code:
public class TestJpaRead {
private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("org.hibernate.tutorial.jpa");
public static void main(String[] args) {
LOG.debug("first time");
countRow(); //output row size = X
//set break point here, and manually insert an new row by using mysql client
LOG.debug("second time");
countRow(); //should output row size = X + 1, but it is still X
}
public static void countRow() {
EntityManager em = emf.createEntityManager();
Query query = em.createQuery("SELECT a FROM " + Report.class.getSimpleName() + " a");
List result = query.getResultList();
LOG.debug("countRow: {}", result.size());
em.close();
}
}
and here is my persistence.xml (nothing special):
<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_2_0.xsd"
version="2.0">
<persistence-unit name="org.hibernate.tutorial.jpa" transaction-type="RESOURCE_LOCAL">
<description>
Persistence unit for the JPA tutorial of the Hibernate Getting Started Guide
</description>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/foo" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="bar" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="auto" />
</properties>
</persistence-unit>
Thanks!
From MySQL query log, I find the reason of the problem:
48 Query SET autocommit=0
140606 11:35:41 48 Query select report0_.id from Report report0_ /*countRow()*/
48 Query SHOW WARNINGS
140606 11:35:42 48 Query select report0_.id from Report report0_ /*countRow()*/
48 Query SHOW WARNINGS
Hibernate does not work in the autocommit mode by default.
em.close() does not implicit commit or rollback the transaction, i.e., the JDBC connection and transaction is still alive/open.
This is what I misunderstood. (emf.close() will actually close the connection.)
When you get EntityManager from emf.createEntityManager(), the new
EntityManager may reuse old JDBC connection. It means that you may
in the transaction opened by previous closed EntityManager.
When you are in a uncommit/opened transaction, and use the default
MySQL isolation level, you cannot see change made by others.
Solution: explicit open and commit the transaction, or tell Hibernate to allow autocommitted JDBC connections. Refs: Select using hibernate

Hibernate can't instantiate id generator in Spring project with multiple data sources

I have a Spring project using Hibernate with two data sources (db2 and sql-server).
As soon as I add
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SOME_SEQ")
to a column field in my entity class, I get a BeanCreationException when creating the sql-server EntityManagerFactory because org.hibernate.dialect.SQLServerDialect doesn't support sequences. The only place this entity is being used, though, is in a DAO that uses a db2 EntityManagerFactory which is using the appropriate dialect.
What am I missing?
Try it with GenerationType=AUTO instead of GenerationType=SEQUENCE.
#GeneratedValue(strategy = GenerationType.AUTO, generator = "SOME_SEQ")
With AUTO hibernate uses the best fitting generation strategy, which is sequences for some databases and autoincrement for others.
(N. B.: I never use annotations but I use mapping files. There <generator class="native"> works well for different database types. GenerationType=AUTO should be the same for annotations.)
Even I faced the same issue and solved it by adding the following option to the JPA persistence-unit configuration
<exclude-unlisted-classes>true</exclude-unlisted-classes>
This option forces the JPA provider to only scan the listed classes instead of the whole surrounding jar, etc.
So it now looks like -
<persistence-unit name="MSSQLBackedPersistenceUnit" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/jdbc/MSSQLServerDS</jta-data-source>
<class>com.example.app.domain.MyEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServer2008Dialect" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>

DDL generation and general persistence.xml settings (OpenJPA)

Summary
I'm trying to run a Java web application JPA 2.0 example. The example application was written to run in Glassfish, using EclipseLink as JPA provider.
I would like to convert it to run in TomEE with OpenJPA as the JPA provider, but I can't any detailed tutorials for getting up and running with OpenJPA.
Problem
I'm having trouble converting persistence.xml to work with OpenJPA instead of EclipseLink. More specifically, the given persistence.xml doesn't specify:
Entity classes. Are these necessary?
The desired JPA provider. Will the container default to something?
The JDBC driver. How do I specify an "in-memory" DB (just for initial testing purposes)?
Also:
How are the DDL generation properties expressed in OpenJPA? I wasn't able to find them the OpenJPA User Guide.
Details
Below is the EclipseLink persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="order" transaction-type="JTA">
<jta-data-source>jdbc/__default</jta-data-source>
<properties>
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
<property name="eclipselink.ddl-generation.output-mode"
value="both" />
</properties>
</persistence-unit>
</persistence>
I have the following Entity classes:
order.entity.LineItem
order.entity.LineItemKey
order.entity.Order
order.entity.Part
order.entity.PartKey
order.entity.Vendor
order.entity.VendorPart
Question
Does anyone know what the equivalent persistence.xml would look like for OpenJPA?
Alternatively, if anyone could point me to an OpenJPA tutorial that covers these issues that would be just as good
If you add the openjpa.jdbc.SynchronizeMappings property as shown below OpenJPA will auto-create all your tables, all your primary keys and all foreign keys exactly to match your objects
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>
Alternatively, you can use EclipseLink in TomEE by just adding the EclipseLink jars to <CATALINA_HOME>/lib/
refer here for Common PersistenceProvider properties
Foreign key constraints
The next line does not create foreign keys:
<property name="openjpa.jdbc.SynchronizeMappings"
value="buildSchema(ForeignKeys=true)"/>
Only creates schema and deletes content of a database.
But if you want create foreign keys, use the following lines:
<property name="openjpa.jdbc.SynchronizeMappings"
value="buildSchema(foreignKeys=true,schemaAction='dropDB,add')"/>
<property name="openjpa.jdbc.SchemaFactory"
value="native(foreignKeys=true)" />
<property name="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict, JoinForeignKeyDeleteAction=restrict"/>
See generated SQL
In another way, if you want to see the SQL output:
<property name="openjpa.Log"
value="DefaultLevel=TRACE,SQL=TRACE" />
NOTE: In order to see the generated output in the TomEE console, you need to change the log level in the file loggin.properties with openjpa.level = FINEST
See more in http://openjpa.apache.org/faq.html

Categories