[DEV] insert ready

This commit is contained in:
Edouard DUPIN 2022-06-24 00:18:23 +02:00
parent 6e015aca72
commit b10fe0bddc
4 changed files with 253 additions and 11 deletions

View File

@ -3,7 +3,8 @@ package org.kar.karusic;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.sql.Date;
import java.util.List;
import java.sql.*;
import org.kar.karusic.annotation.SQLAutoIncrement;
import org.kar.karusic.annotation.SQLComment;
@ -14,6 +15,7 @@ import org.kar.karusic.annotation.SQLPrimaryKey;
import org.kar.karusic.annotation.SQLTableLinkGeneric;
import org.kar.karusic.annotation.SQLTableName;
import org.kar.karusic.annotation.SQLUpdateTime;
import org.kar.karusic.db.DBEntry;
import org.kar.karusic.annotation.SQLCreateTime;
import org.kar.karusic.annotation.SQLDefault;
@ -34,6 +36,12 @@ public class SqlWrapper {
if (type == Boolean.class || type == boolean.class) {
return "tinyint(1)";
}
if (type == Float.class || type == float.class) {
return "float";
}
if (type == Double.class || type == double.class) {
return "double";
}
if (type == Timestamp.class) {
return "timestamp(3)";
}
@ -45,6 +53,217 @@ public class SqlWrapper {
}
throw new Exception("Imcompatible type of element in object for: " + type.getCanonicalName());
}
public <T> T insert(T data) throws Exception {
Class<?> clazz = data.getClass();
//public static NodeSmall createNode(String typeInNode, String name, String descrition, Long parentId) {
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
// real add in the BDD:
try {
String tableName = getTableName(clazz);
boolean createIfNotExist = clazz.getDeclaredAnnotationsByType(SQLIfNotExists.class).length != 0;
StringBuilder query = new StringBuilder();
query.append("INSERT INTO ");
query.append(tableName);
query.append(" (");
boolean firstField = true;
int count = 0;
for (Field elem : clazz.getFields()) {
boolean primaryKey = elem.getDeclaredAnnotationsByType(SQLPrimaryKey.class).length != 0;
if (primaryKey) {
continue;
}
boolean linkGeneric = elem.getDeclaredAnnotationsByType(SQLTableLinkGeneric.class).length != 0;
if (linkGeneric) {
continue;
}
boolean createTime = elem.getDeclaredAnnotationsByType(SQLCreateTime.class).length != 0;
if (createTime) {
continue;
}
boolean updateTime = elem.getDeclaredAnnotationsByType(SQLUpdateTime.class).length != 0;
if (updateTime) {
continue;
}
if (!elem.getClass().isPrimitive()) {
Object tmp = elem.get(data);
if(tmp == null && elem.getDeclaredAnnotationsByType(SQLDefault.class).length != 0) {
continue;
}
}
count++;
String name = elem.getName();
if (firstField) {
firstField = false;
} else {
query.append(",");
}
query.append(" `");
query.append(name);
query.append("`");
}
firstField = true;
query.append(") VALUES (");
for (int iii = 0; iii<count; iii++) {
if (firstField) {
firstField = false;
} else {
query.append(",");
}
query.append("?");
}
query.append(")");
System.out.println("generate the querry: '" + query.toString() + "'");
// prepare the request:
PreparedStatement ps = entry.connection.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS);
Field primaryKeyField = null;
int iii = 1;
for (Field elem : clazz.getFields()) {
boolean primaryKey = elem.getDeclaredAnnotationsByType(SQLPrimaryKey.class).length != 0;
if (primaryKey) {
primaryKeyField = elem;
continue;
}
boolean linkGeneric = elem.getDeclaredAnnotationsByType(SQLTableLinkGeneric.class).length != 0;
if (linkGeneric) {
continue;
}
boolean createTime = elem.getDeclaredAnnotationsByType(SQLCreateTime.class).length != 0;
if (createTime) {
continue;
}
boolean updateTime = elem.getDeclaredAnnotationsByType(SQLUpdateTime.class).length != 0;
if (updateTime) {
continue;
}
Class<?> type = elem.getType();
if (!type.isPrimitive()) {
Object tmp = elem.get(data);
if(tmp == null && elem.getDeclaredAnnotationsByType(SQLDefault.class).length != 0) {
continue;
}
}
count++;
if (type == Long.class) {
Object tmp = elem.get(data);
if (tmp == null) {
ps.setNull(iii++, Types.BIGINT);
} else {
ps.setLong(iii++, (Long)tmp);
}
} else if (type == long.class ) {
ps.setLong(iii++, elem.getLong(data));
} else if (type == Integer.class) {
Object tmp = elem.get(data);
if (tmp == null) {
ps.setNull(iii++, Types.INTEGER);
} else {
ps.setInt(iii++, (Integer)tmp);
}
} else if (type == int.class ) {
ps.setInt(iii++, elem.getInt(data));
} else if (type == Float.class) {
Object tmp = elem.get(data);
if (tmp == null) {
ps.setNull(iii++, Types.FLOAT);
} else {
ps.setFloat(iii++, (Float)tmp);
}
} else if (type == float.class) {
ps.setFloat(iii++, elem.getFloat(data));
} else if (type == Double.class) {
Object tmp = elem.get(data);
if (tmp == null) {
ps.setNull(iii++, Types.DOUBLE);
} else {
ps.setDouble(iii++, (Double)tmp);
}
} else if (type == float.class) {
ps.setDouble(iii++, elem.getDouble(data));
} else if (type == Boolean.class) {
Object tmp = elem.get(data);
if (tmp == null) {
ps.setNull(iii++, Types.INTEGER);
} else {
ps.setBoolean(iii++, (Boolean)tmp);
}
} else if (type == boolean.class) {
ps.setBoolean(iii++, elem.getBoolean(data));
} else if (type == Timestamp.class) {
Object tmp = elem.get(data);
if (tmp == null) {
ps.setNull(iii++, Types.INTEGER);
} else {
ps.setTimestamp(iii++, (Timestamp)tmp);
}
} else if (type == Date.class) {
Object tmp = elem.get(data);
if (tmp == null) {
ps.setNull(iii++, Types.INTEGER);
} else {
ps.setDate(iii++, (Date)tmp);
}
} else if (type == String.class) {
Object tmp = elem.get(data);
if (tmp == null) {
ps.setNull(iii++, Types.VARCHAR);
} else {
ps.setString(iii++, (String)tmp);
}
}
}
// execute the request
int affectedRows = ps.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating node failed, no rows affected.");
}
Long uniqueSQLID = null;
// retreive uid inserted
try (ResultSet generatedKeys = ps.getGeneratedKeys()) {
if (generatedKeys.next()) {
uniqueSQLID = generatedKeys.getLong(1);
} else {
throw new SQLException("Creating node failed, no ID obtained (1).");
}
} catch (Exception ex) {
System.out.println("Can not get the UID key inserted ... ");
ex.printStackTrace();
throw new SQLException("Creating node failed, no ID obtained (2).");
}
if (primaryKeyField != null) {
if (primaryKeyField.getType() == Long.class) {
primaryKeyField.set(data, (Long)uniqueSQLID);
} else if (primaryKeyField.getType() == long.class) {
primaryKeyField.setLong(data, uniqueSQLID);
} else {
System.out.println("Can not manage the primary filed !!!");
}
}
//ps.execute();
} catch (SQLException ex) {
ex.printStackTrace();
}
return data;
}
public void update(Class<?> clazz, long id, String jsonData) throws Exception {
}
public Object get(Class<?> clazz, long id) throws Exception {
return null;
}
public List<Object> gets(Class<?> clazz) throws Exception {
return null;
}
public void delete(Class<?> clazz, long id) throws Exception {
}
public void setDelete(Class<?> clazz, long id) throws Exception {
}
public String createTable(Class<?> clazz) throws Exception {
String tableName = getTableName(clazz);

View File

@ -37,6 +37,15 @@ import org.kar.karusic.util.JWTWrapper;
public class WebLauncher {
public static DBConfig dbConfig;
static {
dbConfig = new DBConfig(ConfigVariable.getDBHost(),
Integer.parseInt(ConfigVariable.getDBPort()),
ConfigVariable.getDBLogin(),
ConfigVariable.getDBPassword(),
ConfigVariable.getDBName());
}
private WebLauncher() {
}
@ -46,7 +55,22 @@ public class WebLauncher {
public static void main(String[] args) {
if (true) {
Track tmpTrack = new Track();
tmpTrack.dataId = (long) 542;
tmpTrack.genderId = (long) 15;
tmpTrack.description = "my beautifull description";
tmpTrack.name = "I am singging in the rain.";
try {
Track tmpTrack2 = new SqlWrapper().insert(tmpTrack);
System.out.print("receive data = " + tmpTrack2);
} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
if (false) {
// generate the BDD:
try {
String out = "";
@ -125,11 +149,6 @@ public class WebLauncher {
//System.out.println(" getDBLogin: '" + ConfigVariable.getDBLogin() + "'");
//System.out.println(" getDBPassword: '" + ConfigVariable.getDBPassword() + "'");
//System.out.println(" getDBName: '" + ConfigVariable.getDBName() + "'");
dbConfig = new DBConfig(ConfigVariable.getDBHost(),
Integer.parseInt(ConfigVariable.getDBPort()),
ConfigVariable.getDBLogin(),
ConfigVariable.getDBPassword(),
ConfigVariable.getDBName());
System.out.println(" ==> " + dbConfig);
System.out.println("OAuth service " + getBaseURI());
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), rc);

View File

@ -30,7 +30,7 @@ public class DBEntry {
ex.printStackTrace();
}
}
/*
public void test() throws SQLException {
String query = "SELECT * FROM user";
Statement st = connection.createStatement();
@ -41,4 +41,5 @@ public class DBEntry {
System.out.println(" - " + user);
}
}
*/
}

View File

@ -12,8 +12,6 @@ CREATE TABLE `node` (
) AUTO_INCREMENT=10;
*/
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.kar.karusic.annotation.SQLIfNotExists;
@ -30,5 +28,10 @@ public class Track extends NodeSmall {
public Long dataId = null;
@SQLTableLinkGeneric
public List<Long> artists = null;
@Override
public String toString() {
return "Track [id=" + id + ", deleted=" + deleted + ", create_date=" + create_date + ", modify_date="
+ modify_date + ", name=" + name + ", description=" + description + ", covers=" + covers + ", genderId="
+ genderId + ", dataId=" + dataId + ", artists=" + artists + "]";
}
}