Spring JDBC:如何创建表?
我使用 Spring JdbcTemplate 和 DAO 模式来访问数据库。我正在寻找一种在 DAO 层中生成表的方法,而不是手动创建数据库表。 我知道我可以使用 JdbcTemplate 来执行语句,我只是在寻找正确的位置来执行它。
有没有最佳实践?
I am using Spring JdbcTemplate
with the DAO pattern to access a database. Instead of creating the database tables manually, I am looking for a way to generate the tables in the DAO layer.
I understand that I can use the JdbcTemplate
to execute statements, I am only looking for the right place to do it.
Is there a best practice for that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 执行(字符串)方法:
但是,正如 beny23 提到的那样,我怀疑是否实际需要在实时应用程序中以编程方式执行此操作。
You can use the execute(String) method:
However as beny23 mentions I would be suspicious of an actual need to do this programatically in a live application.
稍微偏离主题:
您是否绝对需要在代码中执行 DDL 命令?事实上,我确实认为将数据库管理和数据库使用分开是一个好主意。我们这里的 Oracle 数据库安全设置实际上是使用不同的数据库用户 (DB_OWNER) 设置表,而不是由 DB_USER 运行运行 SELECT、INSERT、DELETE 的表。
这可以防止意外删除表或修改架构,并且还允许设置 DB_USER,以便仅授予绝对必要的权限,从而增加了一层安全性。
我认为这取决于您的服务/应用程序的性质,但请考虑在代码内创建表的好处(以及 DDL 代码中可能存在的错误是否会意外破坏生产数据)。
Slightly offtopic:
Is it absolutely necessary that you need to execute the DDL commands from within your code? In fact I do think it is a good idea to have separation between db admin and db usage. Our Oracle database security setup here is actually set up so that the tables are set up using a different database user (DB_OWNER), than the one running the SELECTs, INSERTs, DELETEs are run by DB_USER.
This prevents accidentially deleting tables or modifying the schema and also allows the DB_USER to be setup such that only the privileges that are absolutely necessary are granted, which adds a layer of security.
I suppose it depends on the nature of your service/application, but think about the benefit of creating the tables inside the code (and whether a possible bug in the DDL code could accidentially destroy production data).
使用
(Simple)JdbcOperations
中提供的.update()
方法,它们返回的数字是受影响的行数。它们应该专门用于INSERT
和UPDATE
语句。Use
.update()
methods available in the(Simple)JdbcOperations
, the number they return is the number of affected rows. They're supposed to be specifically used for bothINSERT
andUPDATE
statements.