简体   繁体   中英

jpa many-to-many with additional column

I have a many-to-many relationship with an additional column between two entities. On the owner side entity I have set the cascade type to persist.

    @OneToMany(cascade=CascadeType.PERSIST, fetch = FetchType.LAZY, mappedBy = "definitionType")
    private List<DefinitionProperty> definitionProperties = new ArrayList<DefinitionProperty>();

Here is my new entity which represents table:

@EmbeddedId
protected DefinitionPropertyPK pk;

@JoinColumn(name = "dtid", referencedColumnName = "id", insertable = false, updatable = false)
@ManyToOne(optional = false)
private DefinitionType definitionType;
@JoinColumn(name = "prid", referencedColumnName = "id", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Property property;
@Column(name = "initial_value", insertable = false, updatable = false)
@Basic(optional = false)
private String initialValue;

The problem is when I persist the owner object it will be inserted in database but nothing will be created in join table and I get 'Cannot insert the value NULL into column 'initial_value'' Exception. I don't know why it is null because I have set it in service code.

Call: INSERT INTO definition_property (initial_value, dtid, prid) VALUES (?, ?, ?)
    bind => [3 parameters bound]

Here is my service code and how I create new objects and set their values.

DefinitionType definitionType = new DefinitionType();
        String propertyIds[] = idProperty.split(",");
        String propertyVals[] = propertyValues.split(",");
        for (int i = 0; i < propertyIds.length; i++) {
            Property property = propertyDao.find(Integer.parseInt(propertyIds[i]));
            DefinitionProperty dp = new DefinitionProperty();

            if (propertyVals[i] != "" || propertyVals[i]!=null) {
            dp.setInitialValue(propertyVals[i]);
            } else {
            dp.setInitialValue(property.getInitialValue());
        }
            dp.setDefinitionType(definitionType);
            dp.setProperty(property);
            definitionType.getDefinitionProperties().add(dp);
         }          
        definitionTypeDao.persist(definitionType);

You can find all codes here .

are you sure about this statement

dp.setInitialValue(propertyVals[i]);

propertyVals[i] is not null

'optional' talks about property and field values and suggests that this feature should be evaluated within the runtime.

我通过将@EmbeddedId更改为@IdClass并从中间实体类中删除insertable = false,updatable = false来解决了,现在一切正常。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM