![JAR search and dependency download from the Maven repository](/logo.png)
com.yuxuan66.core.basis.BasisModel Maven / Gradle / Ivy
package com.yuxuan66.core.basis;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;
import java.util.UUID;
import com.yuxuan66.core.db.ConnectionManager;
import com.yuxuan66.core.db.anno.Column;
import com.yuxuan66.core.db.anno.enums.PrimaryKeyType;
import com.yuxuan66.core.db.make.MakeUtils;
import com.yuxuan66.core.db.make.SQL;
public abstract class BasisModel {
@Column(notDB = true)
ConnectionManager cm = ConnectionManager.getInstance();
private Object that;
@SuppressWarnings("unchecked")
public T insert() throws Exception {
that = this;
List fields = MakeUtils.getColumns(that);
String sql = new SQL() {
{
INSERT_INTO(MakeUtils.getTableName(that));
PrimaryKeyType keyType = MakeUtils.getIdType(that);
String idName = MakeUtils.getIdName(that);
boolean isId = !"".equals(idName);
if (keyType == PrimaryKeyType.UUID && isId) {
VALUES(idName, UUID.randomUUID().toString());
}
if (keyType == PrimaryKeyType.UUID && isId) {
VALUES(idName, MakeUtils.getFieidVal(that, idName).toString());
}
for (String field : fields) {
VALUES(field, "?");
}
}
}.toString();
Connection conn = cm.getConnection("default");
// 2.获取用于向数据库发送sql语句的statement
PreparedStatement st = null;
if (MakeUtils.iskey(that)) {
st = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
} else {
st = conn.prepareStatement(sql);
}
for (int i = 1; i <= fields.size(); i++) {
st.setObject(i, MakeUtils.getFieidVal(that, fields.get(i - 1)));
}
Object result = st.executeUpdate();
ResultSet rs = null;
if (MakeUtils.iskey(that)) {
rs = st.getGeneratedKeys();
if (rs.next()) {
result = (T) rs.getObject(1);
}
}
rs.close();
st.close();
conn.close();
return (T) result;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy