使用EclipseLink,在每个新连接上向数据库发送语句

时间:2011-06-01 17:47:00

标签: sqlite jpa eclipselink

我正在使用EclipseLink访问SQLite数据库。默认情况下,SQLite由于向后兼容性,不会强制执行外键约束。可以使用connection.createStatement().execute("PRAGMA foreign_keys=ON")在每个连接的基础上启用外键约束。

使用JDBC时,以下代码可以解决这个问题:

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 'connection'

我如何使用JPA / EclipseLink获得相同的效果?

3 个答案:

答案 0 :(得分:1)

persistence.xml中的

>持久性单元>属性,添加:

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

创建一个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);

    }
}

答案 1 :(得分:0)

您可以使用原生查询。

em.createNativeQuery(“PRAGMA foreign_keys = ON”)。executeUpdate();

您还可以在persistence.xml中注册EclipseLink SessionEventListener,以便始终为每个连接(postAcquireConnection事件)执行此操作。

您也可以在数据库上配置它,以避免在每个连接上执行此SQL。

答案 2 :(得分:0)

SQLite的Xerial JDBC-Driver支持在DriverManager.getConnection()中将“foreign_keys”PRAGMA设置为属性:

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

另见java.org.sqlite.SQLiteConfig

有没有办法使用EclipseLink将这种特定于JDBC-Driver的连接属性添加到persistance.xml? 简单的方法,只是将它添加到属性部分,对我来说不起作用。

相关问题