jpa many-to-many with additional column

2019-06-03 10:48发布

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.

2条回答
家丑人穷心不美
2楼-- · 2019-06-03 11:03

I solved by changing @EmbeddedId to @IdClass and removing insertable = false, updatable = false from my middle entity class and now everything works.

查看更多
SAY GOODBYE
3楼-- · 2019-06-03 11:05

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.

查看更多
登录 后发表回答