#123 - Mapping - Add support for OneToMany JoinTables

This commit is contained in:
Rob Bygrave
2018-02-20 14:40:21 +13:00
parent 8d0df6541e
commit 81d48d67a7
22 changed files with 478 additions and 88 deletions
@@ -191,6 +191,11 @@ public interface BeanCollection<E> extends Serializable {
*/
void setModifyListening(ModifyListenMode modifyListenMode);
/**
* Return the current modify listening mode. Can be null for on newly created beans.
*/
ModifyListenMode getModifyListening();
/**
* Add an object to the additions list.
* <p>
@@ -140,6 +140,11 @@ abstract class AbstractBeanCollection<E> implements BeanCollection<E> {
// Support for modify additions deletions etc - ManyToMany
// ---------------------------------------------------------
@Override
public ModifyListenMode getModifyListening() {
return modifyListenMode;
}
/**
* set modifyListening to be on or off.
*/
@@ -541,17 +541,14 @@ public class BaseTableDdl implements TableDdl {
boolean inlineUniqueWhenNullable = platformDdl.isInlineUniqueWhenNullable();
List<Column> columns = createTable.getColumn();
List<Column> columns = new WriteUniqueConstraint(createTable.getColumn()).uniqueKeys();
for (Column column : columns) {
if (!Boolean.TRUE.equals(column.isPrimaryKey())
&& (hasValue(column.getUnique()) || hasValue(column.getUniqueOneToOne()))) {
if (Boolean.TRUE.equals(column.isNotnull()) || inlineUniqueWhenNullable) {
// normal mechanism for adding unique constraint
inlineUniqueConstraintSingle(apply, column);
} else {
// MsSqlServer & DB2 specific mechanism for adding unique constraints (that allow nulls)
externalUnique.add(column);
}
if (Boolean.TRUE.equals(column.isNotnull()) || inlineUniqueWhenNullable) {
// normal mechanism for adding unique constraint
inlineUniqueConstraintSingle(apply, column);
} else {
// SqlServer & DB2 specific mechanism for adding unique constraints (that allow nulls)
externalUnique.add(column);
}
}
}
@@ -0,0 +1,47 @@
package io.ebeaninternal.dbmigration.ddlgeneration.platform;
import io.ebeaninternal.dbmigration.migration.Column;
import java.util.ArrayList;
import java.util.List;
class WriteUniqueConstraint {
private final List<Column> primaryKeys = new ArrayList<>();
private final List<Column> uniqueKeys = new ArrayList<>();
WriteUniqueConstraint(List<Column> columns) {
// filter for unique and primary keys
for (Column column : columns) {
if (Boolean.TRUE.equals(column.isPrimaryKey())) {
primaryKeys.add(column);
}
if (hasValue(column.getUnique()) || hasValue(column.getUniqueOneToOne())){
uniqueKeys.add(column);
}
}
}
/**
* Return true if null or trimmed string is empty.
*/
boolean hasValue(String value) {
return value != null && !value.trim().isEmpty();
}
/**
* Return the single columns with unique constraints (that are not the primary key).
*/
public List<Column> uniqueKeys() {
if (uniqueKeys.isEmpty() || primaryKeys.size() > 1) {
// all single column unique constraints are valid
return uniqueKeys;
}
// filter out PFK
for (Column primaryKey : primaryKeys) {
uniqueKeys.remove(primaryKey);
}
return uniqueKeys;
}
}
@@ -408,7 +408,6 @@ public class MTable {
* Return all the columns (excluding columns marked as dropped).
*/
public Collection<MColumn> allColumns() {
return columns.values();
}
@@ -9,7 +9,6 @@ import io.ebeaninternal.server.deploy.BeanPropertyAssocMany;
import io.ebeaninternal.server.deploy.TableJoin;
import io.ebeaninternal.server.deploy.TableJoinColumn;
/**
* Add the intersection table to the model.
*/
@@ -32,7 +31,7 @@ public class ModelBuildIntersectionTable {
this.tableJoin = manyProp.getTableJoin();
}
public void build() {
public MTable build() {
intersectionTable = createTable();
MTable existingTable = ctx.addTable(intersectionTable);
@@ -47,6 +46,7 @@ public class ModelBuildIntersectionTable {
ctx.createDraft(intersectionTable, false);
}
return intersectionTable;
}
private void buildFkConstraints() {
@@ -17,6 +17,7 @@ import io.ebeaninternal.server.deploy.TableJoinColumn;
import io.ebeaninternal.server.deploy.id.ImportedId;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
@@ -120,7 +121,7 @@ public class ModelBuildPropertyVisitor extends BaseTablePropertyVisitor {
@Override
public void visitMany(BeanPropertyAssocMany<?> p) {
if (p.isManyToMany()) {
if (p.hasJoinTable()) {
if (p.getMappedBy() == null) {
// only create on other 'owning' side
@@ -130,7 +131,15 @@ public class ModelBuildPropertyVisitor extends BaseTablePropertyVisitor {
// build the create table and fkey constraints
// putting the DDL into ctx for later output as we are
// in the middle of rendering the create table DDL
new ModelBuildIntersectionTable(ctx, p).build();
MTable intersectionTable = new ModelBuildIntersectionTable(ctx, p).build();
if (p.isO2mJoinTable()) {
Collection<MColumn> cols = intersectionTable.allColumns();
if (cols.size() == 2) {
// always the second column that we put the unique constraint on
MColumn col = new ArrayList<>(cols).get(1);
col.setUnique(determineUniqueConstraintName(col.getName()));
}
}
}
}
}
@@ -1138,14 +1138,16 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
if (prop.getMappedBy() == null) {
// if we are doc store only we are done
// this allowes the use of @OneToMany in @DocStore - Entities
// this allows the use of @OneToMany in @DocStore - Entities
if (info.getDescriptor().isDocStoreOnly()) {
prop.setUnidirectional();
return;
}
if (!findMappedBy(prop)) {
makeUnidirectional(info, prop);
if (!prop.isO2mJoinTable()) {
makeUnidirectional(info, prop);
}
return;
}
}
@@ -58,6 +58,8 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
*/
private final boolean unidirectional;
private final boolean o2mJoinTable;
/**
* Flag to indicate that the target has a order column to auto populate.
*/
@@ -114,6 +116,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
public BeanPropertyAssocMany(BeanDescriptor<?> descriptor, DeployBeanPropertyAssocMany<T> deploy) {
super(descriptor, deploy);
this.unidirectional = deploy.isUnidirectional();
this.o2mJoinTable = deploy.isO2mJoinTable();
this.hasOrderColumn = deploy.hasOrderColumn();
this.manyToMany = deploy.isManyToMany();
this.manyType = deploy.getManyType();
@@ -139,8 +142,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
if (!isTransient) {
this.help = BeanCollectionHelpFactory.create(this);
if (manyToMany) {
// only manyToMany's have imported properties
if (hasJoinTable()) {
importedId = createImportedId(this, targetDescriptor, tableJoin);
} else {
@@ -169,7 +171,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
sb.append(", ");
}
// these fk columns are either on the intersection (int_) or base table (t0)
String fkTableAlias = isManyToMany() ? "int_" : "t0";
String fkTableAlias = hasJoinTable() ? "int_" : "t0";
sb.append(fkTableAlias).append(".").append(exportedProperties[i].getForeignDbColumn());
}
sb.append(", ").append(fetchOrderBy);
@@ -178,7 +180,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
}
String delStmt;
if (manyToMany) {
if (hasJoinTable()) {
delStmt = "delete from " + inverseJoin.getTable() + " where ";
} else {
delStmt = "delete from " + targetDescriptor.getBaseTable() + " where ";
@@ -347,8 +349,8 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
*/
private void addWhereParentIdIn(SpiQuery<?> query, List<Object> parentIds) {
String tableAlias = manyToMany ? "int_." : "t0.";
if (manyToMany) {
String tableAlias = hasJoinTable() ? "int_." : "t0.";
if (hasJoinTable()) {
query.setM2MIncludeJoin(inverseJoin);
}
String rawWhere = deriveWhereParentIdSql(true, tableAlias);
@@ -475,12 +477,12 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
StringBuilder sb = new StringBuilder(50);
SpiQuery<?> query = request.getQueryRequest().getQuery();
if (manyToMany) {
if (hasJoinTable()) {
sb.append(query.isAsDraft() ? intersectionDraftTable : intersectionPublishTable);
} else {
sb.append(targetDescriptor.getBaseTable(query.getTemporalMode()));
}
if (softDelete && manyToMany) {
if (softDelete && hasJoinTable()) {
sb.append(" x join ");
sb.append(targetDescriptor.getBaseTable(query.getTemporalMode()));
sb.append(" x2 on ");
@@ -497,7 +499,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
exportedProperties[i].appendWhere(sb, "x.", path);
}
if (softDelete) {
String alias = (manyToMany) ? "x2" : "x";
String alias = hasJoinTable() ? "x2" : "x";
sb.append(" and ").append(targetDescriptor.getSoftDeletePredicate(alias));
}
return sb.toString();
@@ -574,6 +576,20 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
return manyType;
}
/**
* Return true if this is many to many.
*/
public boolean hasJoinTable() {
return manyToMany || o2mJoinTable;
}
/**
* Return true if this is a one to many with a join table.
*/
public boolean isO2mJoinTable() {
return o2mJoinTable;
}
/**
* Return true if this is many to many.
*/
@@ -661,7 +677,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
public void addSelectExported(DbSqlContext ctx, String tableAlias) {
String alias = manyToMany ? "int_" : tableAlias;
String alias = hasJoinTable() ? "int_" : tableAlias;
if (alias == null) {
alias = "t0";
}
@@ -694,45 +710,6 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
return sb.toString();
}
// public void setPredicates(SpiQuery<?> query, EntityBean parentBean) {
//
// if (manyToMany){
// // for ManyToMany lazy loading we need to include a
// // join to the intersection table. The predicate column
// // is not on the 'destination many table'.
// query.setIncludeTableJoin(inverseJoin);
// }
//
// if (embeddedExportedProperties) {
// // use the EmbeddedId object instead of the parentBean
// BeanProperty idProp = descriptor.getIdProperty();
// parentBean = (EntityBean)idProp.getValue(parentBean);
// }
//
// for (int i = 0; i < exportedProperties.length; i++) {
// Object val = exportedProperties[i].getValue(parentBean);
// String fkColumn = exportedProperties[i].getForeignDbColumn();
// if (!manyToMany){
// fkColumn = targetDescriptor.getBaseTableAlias()+"."+fkColumn;
// } else {
// // use hard coded alias for intersection table
// fkColumn = "int_."+fkColumn;
// }
// query.where().eq(fkColumn, val);
// }
//
// if (extraWhere != null){
// // replace the table alias place holder
// String ta = targetDescriptor.getBaseTableAlias();
// String where = StringHelper.replaceString(extraWhere, "${ta}", ta);
// query.where().raw(where);
// }
//
// if (fetchOrderBy != null){
// query.order(fetchOrderBy);
// }
// }
/**
* Create the array of ExportedProperty used to build reference objects.
*/
@@ -776,7 +753,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
String searchTable;
TableJoinColumn[] columns;
if (manyToMany) {
if (hasJoinTable()) {
// look for column going to intersection
columns = intersectionJoin.columns();
searchTable = intersectionJoin.getTable();
@@ -1024,4 +1001,14 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
return liveMap;
}
public boolean isIncludeCascadeSave() {
// Note ManyToMany always included as we always 'save'
// the relationship via insert/delete of intersection table
// REMOVALS means including PrivateOwned relationships
return cascadeInfo.isSave() || hasJoinTable() || ModifyListenMode.REMOVALS == modifyListenMode;
}
public boolean isIncludeCascadeDelete() {
return cascadeInfo.isDelete() || o2mJoinTable || ModifyListenMode.REMOVALS == modifyListenMode;
}
}
@@ -21,6 +21,8 @@ public class DeployBeanPropertyAssocMany<T> extends DeployBeanPropertyAssoc<T> {
*/
private boolean manyToMany;
private boolean o2mJoinTable;
/**
* Flag to indicate this is a unidirectional relationship.
*/
@@ -220,4 +222,14 @@ public class DeployBeanPropertyAssocMany<T> extends DeployBeanPropertyAssoc<T> {
public boolean hasOrderColumn() {
return orderColumn != null;
}
public boolean isO2mJoinTable() {
return o2mJoinTable;
}
public void setO2mJoinTable() {
this.o2mJoinTable = true;
setModifyListenMode(ModifyListenMode.ALL);
}
}
@@ -1,6 +1,5 @@
package io.ebeaninternal.server.deploy.meta;
import io.ebean.bean.BeanCollection.ModifyListenMode;
import io.ebeaninternal.server.deploy.BeanDescriptor;
import io.ebeaninternal.server.deploy.BeanDescriptorMap;
import io.ebeaninternal.server.deploy.BeanProperty;
@@ -437,17 +436,12 @@ public class DeployBeanPropertyLists {
for (BeanPropertyAssocMany<?> prop : manys) {
switch (mode) {
case Save:
if (prop.getCascadeInfo().isSave() || prop.isManyToMany()
|| ModifyListenMode.REMOVALS == prop.getModifyListenMode()) {
// Note ManyToMany always included as we always 'save'
// the relationship via insert/delete of intersection table
// REMOVALS means including PrivateOwned relationships
if (prop.isIncludeCascadeSave()) {
list.add(prop);
}
break;
case Delete:
if (prop.getCascadeInfo().isDelete() || ModifyListenMode.REMOVALS == prop.getModifyListenMode()) {
// REMOVALS means including PrivateOwned relationships
if (prop.isIncludeCascadeDelete()) {
list.add(prop);
}
break;
@@ -122,8 +122,10 @@ class AnnotationAssocManys extends AnnotationParser {
readJoinTable(joinTable, prop);
} else {
// OneToMany in theory
prop.getTableJoin().addJoinColumn(true, joinTable.joinColumns(), beanTable);
// OneToMany with @JoinTable
prop.setO2mJoinTable();
readJoinTable(joinTable, prop);
manyToManyDefaultJoins(prop);
}
}
@@ -825,7 +825,7 @@ public final class DefaultPersister implements Persister {
private void saveMany(SaveManyPropRequest saveMany, boolean insertMode) {
if (saveMany.getMany().isManyToMany()) {
if (saveMany.getMany().hasJoinTable()) {
// check if we can save the m2m intersection in this direction
// we only allow one direction based on first traversed basis
@@ -925,13 +925,19 @@ public final class DefaultPersister implements Persister {
throw new PersistenceException(msg);
}
if (!vanillaCollection) {
((BeanCollection<?>) value).modifyReset();
BeanCollection<?> manyValue = (BeanCollection<?>) value;
setListenMode(manyValue, prop);
manyValue.modifyReset();
}
} else {
// BeanCollection so get the additions/deletions
BeanCollection<?> manyValue = (BeanCollection<?>) value;
additions = manyValue.getModifyAdditions();
deletions = manyValue.getModifyRemovals();
if (setListenMode(manyValue, prop)) {
additions = manyValue.getActualDetails();
} else {
additions = manyValue.getModifyAdditions();
deletions = manyValue.getModifyRemovals();
}
// reset so the changes are only processed once
manyValue.modifyReset();
}
@@ -986,6 +992,19 @@ public final class DefaultPersister implements Persister {
t.depth(-1);
}
/**
* Check if we need to set the listen mode (on new collections persisted for the first time).
*/
private boolean setListenMode(BeanCollection<?> manyValue, BeanPropertyAssocMany<?> prop) {
ModifyListenMode mode = manyValue.getModifyListening();
if (mode == null) {
// new collection persisted for the first time
manyValue.setModifyListening(prop.getModifyListenMode());
return true;
}
return false;
}
private int deleteAssocManyIntersection(EntityBean bean, BeanPropertyAssocMany<?> many, Transaction t, boolean publish) {
// delete all intersection rows for this bean
@@ -1039,7 +1058,7 @@ public final class DefaultPersister implements Persister {
// Many's with delete cascade
BeanPropertyAssocMany<?>[] manys = desc.propertiesManyDelete();
for (BeanPropertyAssocMany<?> many : manys) {
if (many.isManyToMany()) {
if (many.hasJoinTable()) {
if (!softDelete) {
// delete associated rows from intersection table (but not during soft delete)
deleteAssocManyIntersection(parentBean, many, t, request.isPublish());
@@ -175,7 +175,7 @@ class SaveManyPropRequest {
if (detailBean instanceof EntityBean) {
EntityBean detail = (EntityBean) detailBean;
EntityBeanIntercept ebi = detail._ebean_getIntercept();
if (many.isManyToMany()) {
if (many.hasJoinTable()) {
skipSavingThisBean = targetDescriptor.isReference(ebi);
} else {
if (orderColumn != null) {
@@ -12,8 +12,8 @@ import io.ebeaninternal.api.SpiQuery.Mode;
import io.ebeaninternal.server.deploy.BeanDescriptor;
import io.ebeaninternal.server.deploy.BeanProperty;
import io.ebeaninternal.server.deploy.BeanPropertyAssoc;
import io.ebeaninternal.server.deploy.BeanPropertyAssocOne;
import io.ebeaninternal.server.deploy.BeanPropertyAssocMany;
import io.ebeaninternal.server.deploy.BeanPropertyAssocOne;
import io.ebeaninternal.server.deploy.DbReadContext;
import io.ebeaninternal.server.deploy.DbSqlContext;
import io.ebeaninternal.server.deploy.InheritInfo;
@@ -597,7 +597,7 @@ class SqlTreeNodeBean implements SqlTreeNode {
if (nodeBeanProp instanceof BeanPropertyAssocMany<?>) {
BeanPropertyAssocMany<?> manyProp = (BeanPropertyAssocMany<?>) nodeBeanProp;
if (manyProp.isManyToMany()) {
if (manyProp.hasJoinTable()) {
String alias = ctx.getTableAlias(prefix);
String[] split = SplitName.split(prefix);
@@ -105,7 +105,7 @@ class SqlTreeNodeExtraJoin implements SqlTreeNode {
if (assocBeanProperty instanceof BeanPropertyAssocMany<?>) {
BeanPropertyAssocMany<?> manyProp = (BeanPropertyAssocMany<?>) assocBeanProperty;
if (manyProp.isManyToMany()) {
if (manyProp.hasJoinTable()) {
manyToMany = true;
@@ -96,7 +96,7 @@ class SqlTreeNodeManyWhereJoin implements SqlTreeNode {
} else {
BeanPropertyAssocMany<?> manyProp = (BeanPropertyAssocMany<?>) nodeBeanProp;
if (!manyProp.isManyToMany()) {
if (!manyProp.hasJoinTable()) {
manyProp.addJoin(joinType, parentAlias, alias, ctx);
} else {