[英]Dynamic column in sql/jdbc query
I am a student of Computer Science. 我是计算机科学系的学生。 Now I am working on a project with jdbc.
现在,我正在使用jdbc进行项目。 I have to table in database -
USER
, ROLE
. 我必须在数据库中使用表
USER
, ROLE
。
Where each USER
have a one or multiple ROLE
. 每个
USER
都有一个或多个ROLE
。 I save the ROLE.ID
(primary key or ROLE
) in USER.ROLE_ID
column. 我将
ROLE.ID
(主键或ROLE
)保存在USER.ROLE_ID
列中。
In java code level I have two entity class also - User.java
and Role.java
. 在Java代码中的水平,我有两个实体类也-
User.java
和Role.java
。 I can make the simple SQL query with joining these tables. 我可以通过加入这些表来进行简单的SQL查询。
Please see the following queries - 请查看以下查询-
1. Selecting USER.NAME
and ROLE.NAME
for USER.NAME='admin'
- 1.为
USER.NAME='admin'
选择USER.NAME
和ROLE.NAME
SELECT USER.NAME, ROLE.NAME FROM USER, ROLE
WHERE USER.ROLE_ID = ROLE.ROLE_ID
AND USER.NAME='admin';
2. Selecting USER.ID
and ROLE.ID
for the USER.NAME='admin'
- 2.为
USER.NAME='admin'
选择USER.ID
和ROLE.ID
SELECT USER.ID, ROLE.ID FROM USER, ROLE
WHERE USER.ROLE_ID = ROLE.ROLE_ID
AND USER.NAME='admin';
I have to make 2 different queries ONLY for the different columns I am selecting. 我只需要对要选择的不同列进行2个不同的查询。 Here most of the query is same.
这里大多数查询是相同的。 My question is can I do something so that I can dynamically select different (in first case - USER.NAME, ROLE.NAME and Second case USER.ID, ROLE.ID) types of column using a single query?
我的问题是我可以做些什么,以便可以使用单个查询动态选择不同的列类型(第一种情况-USER.NAME,ROLE.NAME和第二种情况USER.ID,ROLE.ID)?
No, You will not have anything like this from JDBC.You have to write your custom function for this. 不,您将不会从JDBC中获得任何类似信息。您必须为此编写自定义函数。
In my opinion, you should just make a function which is taking two parameters OR the same overloaded functions and then provide them arguments. 在我看来,您应该只创建一个带有两个参数或相同重载函数的函数,然后为其提供参数。
here I am providing you some pseudo code for logic 在这里,我为您提供一些逻辑伪代码
function getData(Param tableName, Param column1, Param column2){
String sql = "SELECT "+column1+"','"+column2+"'
FROM `" + tableName + "` WHERE "+column1+" = "+column2;
}
//overloaded
function getData(Param tableName, Param column1, Param column2,Param column3){
String sql = "SELECT "+column1+"','"+column2+"','"column3+"'
FROM `" + tableName + "` WHERE "+column1+" = "+column2;
}
But if you are ready to use some APIs then I can suggest you two very good API to win your scenario. 但是,如果您准备使用一些API,那么我可以建议您使用两个非常好的API来赢得您的方案。 you should give a try to
你应该尝试
Querydsl Querydsl
JOOQ JOOQ
Apache ddlUtils Apache ddlUtils
squiggle-sql 抽搐-SQL
JaQu JaQu
. 。
What about 关于什么
SELECT USER.ID, USER.NAME, ROLE.ID, ROLE.NAME FROM USER, ROLE
WHERE USER.ROLE_ID = ROLE.ROLE_ID
AND USER.NAME='admin';
? ?
I don't really get the question here to be honest. 老实说,我真的没有这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.