Skip to content

Commit f87ebea

Browse files
committed
Server:新增支持数据库自增 id
1 parent 763d5b4 commit f87ebea

3 files changed

Lines changed: 52 additions & 36 deletions

File tree

APIJSON-Java-Server/APIJSONBoot/src/main/java/apijson/demo/server/DemoSQLConfig.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,11 @@ public String getUserIdKey(String database, String schema, String table) {
6767
return Controller.USER_.equals(table) || Controller.PRIVACY_.equals(table) ? KEY_ID : KEY_USER_ID; // id / userId
6868
}
6969

70+
//return null 则不生成 id,一般用于数据库自增 id
71+
// @Override
72+
// public Object newId(RequestMethod method, String database, String schema, String table) {
73+
// return null;
74+
// }
7075
};
7176
}
7277

APIJSON-Java-Server/APIJSONORM/src/main/java/zuo/biao/apijson/server/AbstractSQLConfig.java

Lines changed: 27 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -685,8 +685,8 @@ public AbstractSQLConfig setJson(List<String> json) {
685685
this.json = json;
686686
return this;
687687
}
688-
689-
688+
689+
690690
@Override
691691
public Subquery getFrom() {
692692
return from;
@@ -856,7 +856,7 @@ public String getColumnString(boolean inSQLJoin) throws Exception {
856856
}
857857
}
858858
else {
859-
// if ((StringUtil.isName(origin) == false || origin.startsWith("_"))) {
859+
// if ((StringUtil.isName(origin) == false || origin.startsWith("_"))) {
860860
if (origin.startsWith("_") || PATTERN_FUNCTION.matcher(origin).matches() == false) {
861861
throw new IllegalArgumentException("字符 " + ckeys[j] + " 不合法!"
862862
+ "预编译模式下 @column:\"column0,column1:alias;function0(arg0,arg1,...);function1(...):alias...\""
@@ -877,7 +877,7 @@ else if (StringUtil.isName(origin)) {
877877
else {
878878
origin = getValue(origin).toString();
879879
}
880-
880+
881881
if (isName && isKeyPrefix()) {
882882
ckeys[j] = tableAlias + "." + origin;
883883
// if (isColumn) {
@@ -1330,7 +1330,7 @@ else if ("!".equals(ce.getKey())) {
13301330

13311331
isItemFirst = false;
13321332
}
1333-
1333+
13341334
if (StringUtil.isEmpty(cs, true)) {//避免SQL条件连接错误
13351335
continue;
13361336
}
@@ -2352,13 +2352,10 @@ public static AbstractSQLConfig newSQLConfig(RequestMethod method, String table,
23522352

23532353
Object idIn = request.get(idInKey); //可能是 id{}:">0"
23542354

2355-
if (method == POST) {
2356-
if (idIn != null) { //不能在这里确定[]的长度,只能在外面传进来
2357-
if ((idIn instanceof List == false) || ((List<?>)idIn).isEmpty()) { // id{}:[] 表示同时插入多条记录
2358-
throw new IllegalArgumentException("POST请求,生成多条记录请用 id{}:[] ! [] 类型为JSONArray且不能为空!");
2359-
}
2360-
} else if (request.get(idKey) == null) {
2361-
request.put(idKey, callback.newId(method, database, schema, table));
2355+
if (method == POST && request.get(idKey) == null) {
2356+
Object newId = callback.newId(method, database, schema, table); // null 表示数据库自增 id
2357+
if (newId != null) {
2358+
request.put(idKey, newId);
23622359
}
23632360
}
23642361

@@ -2430,21 +2427,12 @@ else if (id instanceof Subquery) {}
24302427

24312428
//已经remove了id和id{},以及@key
24322429
Set<String> set = request.keySet(); //前面已经判断request是否为空
2433-
if (method == POST) {//POST操作
2434-
if (set != null && set.isEmpty() == false) { //不能直接return,要走完下面的流程
2435-
List<Object> idList;
2436-
if (id != null) { //单条记录
2437-
if (idIn != null) {
2438-
throw new IllegalArgumentException("POST请求中 id 和 id{} 不能同时存在!");
2439-
}
2440-
2441-
idList = new ArrayList<Object>(1);
2442-
idList.add(id);
2443-
} else { //多条记录
2444-
idList = new ArrayList<Object>((JSONArray) idIn);
2445-
}
2430+
if (method == POST) { //POST操作
2431+
if (idIn != null) {
2432+
throw new IllegalArgumentException("POST 请求中不允许传 " + idInKey + " !");
2433+
}
24462434

2447-
//idIn不为空时,valuesString有多条,唯一的区别就是id
2435+
if (set != null && set.isEmpty() == false) { //不能直接return,要走完下面的流程
24482436
String[] columns = set.toArray(new String[]{});
24492437

24502438
Collection<Object> valueCollection = request.values();
@@ -2454,19 +2442,25 @@ else if (id instanceof Subquery) {}
24542442
throw new Exception("服务器内部错误:\n" + TAG
24552443
+ " newSQLConfig values == null || values.length != columns.length !");
24562444
}
2457-
column = idKey + "," + StringUtil.getString(columns); //set已经判断过不为空
2458-
final int size = columns.length + 1; //以key数量为准
2445+
column = (id == null ? "" : idKey + ",") + StringUtil.getString(columns); //set已经判断过不为空
24592446

2460-
List<List<Object>> valuess = new ArrayList<>(idList.size()); // [idList.size()][]
2447+
List<List<Object>> valuess = new ArrayList<>(1);
24612448
List<Object> items; //(item0, item1, ...)
2462-
for (int i = 0; i < idList.size(); i++) {
2449+
if (id == null) { //数据库自增 id
2450+
items = Arrays.asList(values); //FIXME 是否还需要进行 add 或 remove 操作?Arrays.ArrayList 不允许修改,会抛异常
2451+
}
2452+
else {
2453+
int size = columns.length + (id == null ? 0 : 1); //以key数量为准
2454+
24632455
items = new ArrayList<>(size);
2464-
items.add(idList.get(i)); //第0个就是id
2456+
items.add(id); //idList.get(i)); //第0个就是id
2457+
24652458
for (int j = 1; j < size; j++) {
24662459
items.add(values[j-1]); //从第1个开始,允许"null"
24672460
}
2468-
valuess.add(items);
24692461
}
2462+
2463+
valuess.add(items);
24702464
config.setValues(valuess);
24712465
}
24722466
}
@@ -2612,7 +2606,7 @@ else if (whereList != null && whereList.contains(key)) {
26122606
config.setGroup(group);
26132607
config.setHaving(having);
26142608
config.setOrder(order);
2615-
2609+
26162610
String[] jsonArr = StringUtil.split(json);
26172611
config.setJson(jsonArr == null || jsonArr.length <= 0 ? null : new ArrayList<>(Arrays.asList(jsonArr)));
26182612

APIJSON-Java-Server/APIJSONORM/src/main/java/zuo/biao/apijson/server/AbstractSQLExecutor.java

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
import zuo.biao.apijson.JSONResponse;
4343
import zuo.biao.apijson.Log;
4444
import zuo.biao.apijson.NotNull;
45+
import zuo.biao.apijson.RequestMethod;
4546
import zuo.biao.apijson.StringUtil;
4647

4748
/**executor for query(read) or update(write) MySQL database
@@ -575,7 +576,7 @@ else if (value instanceof Blob) { //FIXME 存的是 abcde,取出来直接就
575576
}
576577
else if (value instanceof Clob) { //SQL Server TEXT 类型 居然走这个
577578
castToJson = true;
578-
579+
579580
StringBuffer sb = new StringBuffer();
580581
BufferedReader br = new BufferedReader(((Clob) value).getCharacterStream());
581582
String s = br.readLine();
@@ -636,7 +637,13 @@ public boolean isJSONType(@NotNull SQLConfig config, ResultSetMetaData rsmd, int
636637
*/
637638
@Override
638639
public PreparedStatement getStatement(@NotNull SQLConfig config) throws Exception {
639-
PreparedStatement statement = getConnection(config).prepareStatement(config.getSQL(config.isPrepared())); //创建Statement对象
640+
PreparedStatement statement; //创建Statement对象
641+
if (config.getMethod() == RequestMethod.POST && config.getId() == null) { //自增id
642+
statement = getConnection(config).prepareStatement(config.getSQL(config.isPrepared()), Statement.RETURN_GENERATED_KEYS);
643+
}
644+
else {
645+
statement = getConnection(config).prepareStatement(config.getSQL(config.isPrepared()));
646+
}
640647
List<Object> valueList = config.isPrepared() ? config.getPreparedValueList() : null;
641648

642649
if (valueList != null && valueList.isEmpty() == false) {
@@ -795,7 +802,17 @@ public ResultSet executeQuery(@NotNull SQLConfig config) throws Exception {
795802

796803
@Override
797804
public int executeUpdate(@NotNull SQLConfig config) throws Exception {
798-
return getStatement(config).executeUpdate(); //PreparedStatement 不用传 SQL
805+
PreparedStatement s = getStatement(config);
806+
int count = s.executeUpdate(); //PreparedStatement 不用传 SQL
807+
808+
if (config.getMethod() == RequestMethod.POST && config.getId() == null) { //自增id
809+
ResultSet rs = s.getGeneratedKeys();
810+
if (rs != null && rs.next()) {
811+
config.setId(rs.getLong(1));//返回插入的主键id
812+
}
813+
}
814+
815+
return count;
799816
}
800817

801818

0 commit comments

Comments
 (0)