Spring JDBC: How to create the tables?

女生的网名这么多〃 提交于 2019-12-21 17:37:11

问题


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?


回答1:


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




回答2:


You can use the execute(String) method:

public void execute(String sql) throws DataAccessException

Issue a single SQL execute, typically a DDL statement.
Specified by: execute in interface JdbcOperations

Parameters: sql - static SQL to execute

Throws: DataAccessException - if there is any problem

However as beny23 mentions I would be suspicious of an actual need to do this programatically in a live application.




回答3:


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 both INSERT and UPDATE statements.



来源:https://stackoverflow.com/questions/2101439/spring-jdbc-how-to-create-the-tables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!