使用 EclipseLink,在每个新连接上向数据库发送一条语句
我正在使用 EclipseLink 访问 SQLite 数据库。默认情况下,由于向后兼容性,SQLite 不强制执行外键约束。可以使用 connection.createStatement().execute("PRAGMAforeign_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'
How will I get the sameeffect with JPA/EclipseLink?
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 'connection'
How would I get the same effect with JPA/EclipseLink?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 persistence.xml 中 >持久性单位>属性,添加:
创建一个类MySessionEventAdapter:
in persistence.xml > persitence-unit > properties, add:
Create a class MySessionEventAdapter:
您可以使用本机查询。
em.createNativeQuery("PRAGMAforeign_keys=ON").executeUpdate();
您还可以在 persistence.xml 中注册一个 EclipseLink SessionEventListener,以便始终对每个连接(postAcquireConnection 事件)执行此操作。
您还可以在数据库上配置它,以避免在每个连接上执行此 SQL。
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.
Xerial JDBC-Driver for SQLite 支持将“foreign_keys”PRAGMA 设置为 DriverManager.getConnection() 中的属性:
另请参阅 java.org.sqlite.SQLiteConfig。
有没有办法使用 EclipseLink 将此类 JDBC 驱动程序特定的连接属性添加到 persistance.xml 中?
这种简单的方法,只是将其添加到属性部分,对我来说不起作用。
The Xerial JDBC-Driver for SQLite supports to set the "foreign_keys" PRAGMA as a property in DriverManager.getConnection():
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.