优化主键的省略配置

This commit is contained in:
开源海哥 2023-07-07 10:50:58 +08:00
parent 125335f544
commit 41c30e9cfc
12 changed files with 64 additions and 34 deletions

View File

@ -22,9 +22,9 @@ import java.lang.annotation.*;
@Target({ElementType.FIELD}) @Target({ElementType.FIELD})
public @interface RelationManyToMany { public @interface RelationManyToMany {
String selfField(); String selfField() default "";
String targetField(); String targetField() default "";
String joinTable(); String joinTable();

View File

@ -22,8 +22,8 @@ import java.lang.annotation.*;
@Target({ElementType.FIELD}) @Target({ElementType.FIELD})
public @interface RelationManyToOne { public @interface RelationManyToOne {
String selfField(); String selfField() default "";
String targetField(); String targetField();
} }

View File

@ -22,7 +22,7 @@ import java.lang.annotation.*;
@Target({ElementType.FIELD}) @Target({ElementType.FIELD})
public @interface RelationOneToMany { public @interface RelationOneToMany {
String selfField(); String selfField() default "";
String targetField(); String targetField();

View File

@ -22,7 +22,7 @@ import java.lang.annotation.*;
@Target({ElementType.FIELD}) @Target({ElementType.FIELD})
public @interface RelationOneToOne { public @interface RelationOneToOne {
String selfField(); String selfField() default "";
String targetField(); String targetField();

View File

@ -587,7 +587,7 @@ public class CommonsDialectImpl implements IDialect {
Object[] tenantIdArgs = tableInfo.buildTenantIdArgs(); Object[] tenantIdArgs = tableInfo.buildTenantIdArgs();
//正常删除 //正常删除
if (StringUtil.isBlank(logicDeleteColumn)) { if (StringUtil.isBlank(logicDeleteColumn)) {
String deleteByIdSql = forDeleteById(tableInfo.getSchema(), tableInfo.getTableName(), tableInfo.getPrimaryKeys()); String deleteByIdSql = forDeleteById(tableInfo.getSchema(), tableInfo.getTableName(), tableInfo.getPrimaryColumns());
if (ArrayUtil.isNotEmpty(tenantIdArgs)) { if (ArrayUtil.isNotEmpty(tenantIdArgs)) {
deleteByIdSql += AND + wrap(tableInfo.getTenantIdColumn()) + IN + buildQuestion(tenantIdArgs.length); deleteByIdSql += AND + wrap(tableInfo.getTenantIdColumn()) + IN + buildQuestion(tenantIdArgs.length);
@ -597,7 +597,7 @@ public class CommonsDialectImpl implements IDialect {
//逻辑删除 //逻辑删除
StringBuilder sql = new StringBuilder(); StringBuilder sql = new StringBuilder();
String[] primaryKeys = tableInfo.getPrimaryKeys(); String[] primaryKeys = tableInfo.getPrimaryColumns();
sql.append(UPDATE).append(tableInfo.getWrapSchemaAndTableName(this)); sql.append(UPDATE).append(tableInfo.getWrapSchemaAndTableName(this));
sql.append(SET).append(buildLogicDeletedSet(logicDeleteColumn)); sql.append(SET).append(buildLogicDeletedSet(logicDeleteColumn));
@ -627,7 +627,7 @@ public class CommonsDialectImpl implements IDialect {
//正常删除 //正常删除
if (StringUtil.isBlank(logicDeleteColumn)) { if (StringUtil.isBlank(logicDeleteColumn)) {
String deleteSQL = forDeleteBatchByIds(tableInfo.getSchema(), tableInfo.getTableName(), tableInfo.getPrimaryKeys(), primaryValues); String deleteSQL = forDeleteBatchByIds(tableInfo.getSchema(), tableInfo.getTableName(), tableInfo.getPrimaryColumns(), primaryValues);
//多租户 //多租户
if (ArrayUtil.isNotEmpty(tenantIdArgs)) { if (ArrayUtil.isNotEmpty(tenantIdArgs)) {
@ -644,7 +644,7 @@ public class CommonsDialectImpl implements IDialect {
sql.append(WHERE); sql.append(WHERE);
sql.append(BRACKET_LEFT); sql.append(BRACKET_LEFT);
String[] primaryKeys = tableInfo.getPrimaryKeys(); String[] primaryKeys = tableInfo.getPrimaryColumns();
//多主键的场景 //多主键的场景
if (primaryKeys.length > 1) { if (primaryKeys.length > 1) {
@ -722,7 +722,7 @@ public class CommonsDialectImpl implements IDialect {
Set<String> updateColumns = tableInfo.obtainUpdateColumns(entity, ignoreNulls, false); Set<String> updateColumns = tableInfo.obtainUpdateColumns(entity, ignoreNulls, false);
Map<String, RawValue> rawValueMap = tableInfo.obtainUpdateRawValueMap(entity); Map<String, RawValue> rawValueMap = tableInfo.obtainUpdateRawValueMap(entity);
String[] primaryKeys = tableInfo.getPrimaryKeys(); String[] primaryKeys = tableInfo.getPrimaryColumns();
sql.append(UPDATE).append(tableInfo.getWrapSchemaAndTableName(this)).append(SET); sql.append(UPDATE).append(tableInfo.getWrapSchemaAndTableName(this)).append(SET);
@ -907,7 +907,7 @@ public class CommonsDialectImpl implements IDialect {
buildSelectColumnSql(sql, null, null, null); buildSelectColumnSql(sql, null, null, null);
sql.append(FROM).append(tableInfo.getWrapSchemaAndTableName(this)); sql.append(FROM).append(tableInfo.getWrapSchemaAndTableName(this));
sql.append(WHERE); sql.append(WHERE);
String[] pKeys = tableInfo.getPrimaryKeys(); String[] pKeys = tableInfo.getPrimaryColumns();
for (int i = 0; i < pKeys.length; i++) { for (int i = 0; i < pKeys.length; i++) {
if (i > 0) { if (i > 0) {
sql.append(AND); sql.append(AND);
@ -937,7 +937,7 @@ public class CommonsDialectImpl implements IDialect {
buildSelectColumnSql(sql, null, tableInfo.getDefaultQueryColumn(), null); buildSelectColumnSql(sql, null, tableInfo.getDefaultQueryColumn(), null);
sql.append(FROM).append(tableInfo.getWrapSchemaAndTableName(this)); sql.append(FROM).append(tableInfo.getWrapSchemaAndTableName(this));
sql.append(WHERE); sql.append(WHERE);
String[] primaryKeys = tableInfo.getPrimaryKeys(); String[] primaryKeys = tableInfo.getPrimaryColumns();
String logicDeleteColumn = tableInfo.getLogicDeleteColumnOrSkip(); String logicDeleteColumn = tableInfo.getLogicDeleteColumnOrSkip();
Object[] tenantIdArgs = tableInfo.buildTenantIdArgs(); Object[] tenantIdArgs = tableInfo.buildTenantIdArgs();

View File

@ -38,7 +38,9 @@ class ManyToMany<SelfEntity> extends Relation<SelfEntity> {
private String orderBy; private String orderBy;
public ManyToMany(RelationManyToMany annotation, Class<SelfEntity> entityClass, Field relationField) { public ManyToMany(RelationManyToMany annotation, Class<SelfEntity> entityClass, Field relationField) {
super(annotation.selfField(), annotation.targetField(), entityClass, relationField); super(getDefaultPrimaryProperty(annotation.selfField(), entityClass, "@RelationOneToMany.selfField can not be empty in field: \"" + entityClass.getName() + "." + relationField.getName() + "\""),
getDefaultPrimaryProperty(annotation.targetField(), entityClass, "@RelationOneToMany.targetField can not be empty in field: \"" + entityClass.getName() + "." + relationField.getName() + "\""),
entityClass, relationField);
this.joinTable = annotation.joinTable(); this.joinTable = annotation.joinTable();
this.joinSelfColumn = annotation.joinSelfColumn(); this.joinSelfColumn = annotation.joinSelfColumn();

View File

@ -28,7 +28,8 @@ import static com.mybatisflex.core.query.QueryMethods.column;
class ManyToOne<SelfEntity> extends Relation<SelfEntity> { class ManyToOne<SelfEntity> extends Relation<SelfEntity> {
public ManyToOne(RelationManyToOne annotation, Class<SelfEntity> entityClass, Field relationField) { public ManyToOne(RelationManyToOne annotation, Class<SelfEntity> entityClass, Field relationField) {
super(annotation.selfField(), annotation.targetField(), entityClass, relationField); super(getDefaultPrimaryProperty(annotation.selfField(), entityClass, "@RelationOneToMany.selfField can not be empty in field: \"" + entityClass.getName() + "." + relationField.getName() + "\""),
annotation.targetField(), entityClass, relationField);
} }
@Override @Override

View File

@ -36,7 +36,8 @@ class OneToMany<SelfEntity> extends Relation<SelfEntity> {
public OneToMany(RelationOneToMany annotation, Class<SelfEntity> entityClass, Field relationField) { public OneToMany(RelationOneToMany annotation, Class<SelfEntity> entityClass, Field relationField) {
super(annotation.selfField(), annotation.targetField(), entityClass, relationField); super(getDefaultPrimaryProperty(annotation.selfField(),entityClass,"@RelationOneToMany.selfField can not be empty in field: \"" + entityClass.getName() + "." + relationField.getName() + "\""),
annotation.targetField(), entityClass, relationField);
this.orderBy = annotation.orderBy(); this.orderBy = annotation.orderBy();
this.limit = annotation.limit(); this.limit = annotation.limit();
} }

View File

@ -28,7 +28,8 @@ import static com.mybatisflex.core.query.QueryMethods.column;
class OneToOne<SelfEntity> extends Relation<SelfEntity> { class OneToOne<SelfEntity> extends Relation<SelfEntity> {
public OneToOne(RelationOneToOne annotation, Class<SelfEntity> entityClass, Field relationField) { public OneToOne(RelationOneToOne annotation, Class<SelfEntity> entityClass, Field relationField) {
super(annotation.selfField(), annotation.targetField(), entityClass, relationField); super(getDefaultPrimaryProperty(annotation.selfField(), entityClass, "@RelationOneToOne.selfField can not be empty in field: \"" + entityClass.getName() + "." + relationField.getName() + "\""),
annotation.targetField(), entityClass, relationField);
} }

View File

@ -16,11 +16,14 @@
package com.mybatisflex.core.relation; package com.mybatisflex.core.relation;
import com.mybatisflex.core.BaseMapper; import com.mybatisflex.core.BaseMapper;
import com.mybatisflex.core.exception.FlexExceptions;
import com.mybatisflex.core.query.QueryWrapper; import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.table.IdInfo;
import com.mybatisflex.core.table.TableInfo; import com.mybatisflex.core.table.TableInfo;
import com.mybatisflex.core.table.TableInfoFactory; import com.mybatisflex.core.table.TableInfoFactory;
import com.mybatisflex.core.util.ClassUtil; import com.mybatisflex.core.util.ClassUtil;
import com.mybatisflex.core.util.FieldWrapper; import com.mybatisflex.core.util.FieldWrapper;
import com.mybatisflex.core.util.StringUtil;
import org.apache.ibatis.reflection.Reflector; import org.apache.ibatis.reflection.Reflector;
import org.apache.ibatis.reflection.TypeParameterResolver; import org.apache.ibatis.reflection.TypeParameterResolver;
@ -167,4 +170,19 @@ abstract class Relation<SelfEntity> {
public Class<?> getMappingType() { public Class<?> getMappingType() {
return relationFieldWrapper.getMappingType(); return relationFieldWrapper.getMappingType();
} }
protected static String getDefaultPrimaryProperty(String key,Class<?> entityClass,String message){
if (StringUtil.isNotBlank(key)){
return key;
}
TableInfo tableInfo = TableInfoFactory.ofEntityClass(entityClass);
List<IdInfo> primaryKeyList = tableInfo.getPrimaryKeyList();
if (primaryKeyList == null || primaryKeyList.size() != 1){
throw FlexExceptions.wrap(message);
}
return primaryKeyList.get(0).getProperty();
}
} }

View File

@ -78,7 +78,7 @@ public class TableInfo {
private String[] columns = new String[0]; private String[] columns = new String[0];
//主键字段 //主键字段
private String[] primaryKeys = new String[0]; private String[] primaryColumns = new String[0];
// 默认查询列 // 默认查询列
private String[] defaultColumns = new String[0]; private String[] defaultColumns = new String[0];
@ -261,12 +261,12 @@ public class TableInfo {
this.columns = columns; this.columns = columns;
} }
public String[] getPrimaryKeys() { public String[] getPrimaryColumns() {
return primaryKeys; return primaryColumns;
} }
public void setPrimaryKeys(String[] primaryKeys) { public void setPrimaryColumns(String[] primaryColumns) {
this.primaryKeys = primaryKeys; this.primaryColumns = primaryColumns;
} }
@ -354,12 +354,12 @@ public class TableInfo {
void setPrimaryKeyList(List<IdInfo> primaryKeyList) { void setPrimaryKeyList(List<IdInfo> primaryKeyList) {
this.primaryKeyList = primaryKeyList; this.primaryKeyList = primaryKeyList;
this.primaryKeys = new String[primaryKeyList.size()]; this.primaryColumns = new String[primaryKeyList.size()];
List<String> insertIdFields = new ArrayList<>(); List<String> insertIdFields = new ArrayList<>();
for (int i = 0; i < primaryKeyList.size(); i++) { for (int i = 0; i < primaryKeyList.size(); i++) {
IdInfo idInfo = primaryKeyList.get(i); IdInfo idInfo = primaryKeyList.get(i);
primaryKeys[i] = idInfo.getColumn(); primaryColumns[i] = idInfo.getColumn();
if (idInfo.getKeyType() != KeyType.Auto && (idInfo.getBefore() != null && idInfo.getBefore())) { if (idInfo.getKeyType() != KeyType.Auto && (idInfo.getBefore() != null && idInfo.getBefore())) {
insertIdFields.add(idInfo.getColumn()); insertIdFields.add(idInfo.getColumn());
@ -455,11 +455,11 @@ public class TableInfo {
*/ */
public String[] obtainInsertColumnsWithPk(Object entity, boolean ignoreNulls) { public String[] obtainInsertColumnsWithPk(Object entity, boolean ignoreNulls) {
if (!ignoreNulls) { if (!ignoreNulls) {
return ArrayUtil.concat(primaryKeys, columns); return ArrayUtil.concat(primaryColumns, columns);
} else { } else {
MetaObject metaObject = EntityMetaObject.forObject(entity, reflectorFactory); MetaObject metaObject = EntityMetaObject.forObject(entity, reflectorFactory);
List<String> retColumns = new ArrayList<>(); List<String> retColumns = new ArrayList<>();
for (String primaryKey : primaryKeys) { for (String primaryKey : primaryColumns) {
Object value = buildColumnSqlArg(metaObject, primaryKey); Object value = buildColumnSqlArg(metaObject, primaryKey);
if (value == null) { if (value == null) {
throw new IllegalArgumentException("Entity Primary Key value must not be null."); throw new IllegalArgumentException("Entity Primary Key value must not be null.");
@ -528,7 +528,7 @@ public class TableInfo {
continue; continue;
} }
if (!includePrimary && ArrayUtil.contains(primaryKeys, column)) { if (!includePrimary && ArrayUtil.contains(primaryColumns, column)) {
continue; continue;
} }
@ -603,7 +603,7 @@ public class TableInfo {
continue; continue;
} }
if (!includePrimary && ArrayUtil.contains(primaryKeys, column)) { if (!includePrimary && ArrayUtil.contains(primaryColumns, column)) {
continue; continue;
} }
@ -667,9 +667,9 @@ public class TableInfo {
*/ */
public Object[] buildPkSqlArgs(Object entity) { public Object[] buildPkSqlArgs(Object entity) {
MetaObject metaObject = EntityMetaObject.forObject(entity, reflectorFactory); MetaObject metaObject = EntityMetaObject.forObject(entity, reflectorFactory);
Object[] values = new Object[primaryKeys.length]; Object[] values = new Object[primaryColumns.length];
for (int i = 0; i < primaryKeys.length; i++) { for (int i = 0; i < primaryColumns.length; i++) {
values[i] = buildColumnSqlArg(metaObject, primaryKeys[i]); values[i] = buildColumnSqlArg(metaObject, primaryColumns[i]);
} }
return values; return values;
} }

View File

@ -31,17 +31,24 @@ public class Account implements Serializable {
private int age; private int age;
// @RelationOneToOne(selfField = "id", targetField = "accountId") // @RelationOneToOne(selfField = "id", targetField = "accountId")
// @RelationOneToOne(targetField = "accountId")
private IDCard idCard; private IDCard idCard;
@RelationOneToMany(selfField = "id", targetField = "accountId") // @RelationOneToMany(selfField = "id", targetField = "accountId")
// @RelationOneToMany(targetField = "accountId")
private List<Book> books; private List<Book> books;
// @RelationManyToMany( // @RelationManyToMany(
// joinTable = "tb_role_mapping", // joinTable = "tb_role_mapping",
// selfField = "id", joinSelfColumn = "account_id", // selfField = "id", joinSelfColumn = "account_id",
// targetField = "id", joinTargetColumn = "role_id" // targetField = "id", joinTargetColumn = "role_id"
// ) // )
@RelationManyToMany(
joinTable = "tb_role_mapping",
joinSelfColumn = "account_id",
joinTargetColumn = "role_id"
)
private List<Role> roles; private List<Role> roles;