开发者

With EclipseLink, send a statement to the database on each new connection

I'm using EclipseLink to access an SQLite database. SQLite, by default, because of backwards compatibility, does not enforce foreign key constraints. Foreign keys constraints can be enabled on per-connection basis using connection.createStatement().execute("PRAGMA foreign_keys=ON").

When using JDBC, the following code does the trick:

Connection connection = DriverManager.getConnection("jdbc:sqlite:example.db");
Statement statement = connection.createStatement();
statement.execute("PRAGMA foreign_keys=ON");
// From now on, foreign key constraints are enforced on 'connectio开发者_JAVA技巧n'

How would I get the same effect with JPA/EclipseLink?


in persistence.xml > persitence-unit > properties, add:

<property name="eclipselink.session-event-listener"
value="com.example.MySessionEventAdapter"/>

Create a class MySessionEventAdapter:

package com.example;

import org.eclipse.persistence.sessions.SessionEvent;
import org.eclipse.persistence.sessions.SessionEventAdapter;

public class MySessionEventAdapter extends SessionEventAdapter {

    @Override
    public void postAcquireClientSession(SessionEvent event) {

        event.getSession().executeNonSelectingSQL("PRAGMA foreign_keys=ON");

        super.postAcquireClientSession(event);

    }
}


You can use a native query.

em.createNativeQuery("PRAGMA foreign_keys=ON").executeUpdate();

You could also register an EclipseLink SessionEventListener in your persistence.xml to have this always done for every connection (postAcquireConnection event).

You may also be able to configure it on your database, to avoid having to execute this SQL on every connection.


The Xerial JDBC-Driver for SQLite supports to set the "foreign_keys" PRAGMA as a property in DriverManager.getConnection():

Properties props = new Properties();
props.put("foreign_keys", "true");
DriverManager.getConnection("jdbc:sqlite:example.db", props);
...

See also java.org.sqlite.SQLiteConfig.

Is there a way to add such JDBC-Driver specific connection properties to persistance.xml with EclipseLink?
The trivial approach, just adding it to the properties-section, did not work for me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜