使用EclipseLink,将语句发送到每个新连接上的数据库

问题描述:

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

当使用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的同样的效果?

您可以使用本机查询。

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

您也可以在persistence.xml中注册一个EclipseLink SessionEventListener,以便始终为每个连接完成此任务(postAcquireConnection事件)。

您也可以在数据库上对其进行配置,以避免必须在每个连接上执行此SQL。

+0

我会在哪里把那条线?我尝试将它放入'SessionEventAdapter'的'postConnect()';但是我从哪里得到'EntityManager'呢?当调用'Persistence.createEntityManagerFactory(“example”)。createEntityManager()'时,'postConnect()'事件被触发。谢谢! – Feuermurmel 2011-06-03 20:42:37

的Xerial JDBC驱动器为SQLite支持来设置 “foreign_keys” PRAGMA如的DriverManager.getConnection()的性质:

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

参见java.org.sqlite.SQLiteConfig

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

persistence.xml中> persitence单位>属性

,添加:

<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); 

    } 
}