Hibernate MapKeyColumn会自动保留吗?

时间:2014-10-16 17:55:37

标签: java hibernate jpa playframework

我有2个实体User& Vehicle通过JoinTable地图与一对多关系&一个列表。如果我在数据库中有持久的User&我在用户列表中添加了一个临时Vehicle(user.vehicles)&用户的地图(user.activeVehicles),它以某种方式触发一个持久性,一旦事务关闭就会抛出错误。例如:

User user = new User();
user.save();
(commit, flush, & close transaction)

Vehicle v = new Vehicle();
user.vehicles.add(v);
user.activeVehicles.put("car", vehicle);


Address address = new Address();
address.save();

此事务将抛出错误

java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: models.Vehicle

以下是2个实体

用户

@Entity
@Table(name = "users")
@TypeDefs({
        @TypeDef(name = "hstoredatestring", typeClass = HstoreUserType.DateString.class)
})
@org.hibernate.annotations.Entity(dynamicUpdate = true)
public class User extends Model
{
    @OneToMany(cascade = CascadeType.ALL, targetEntity = Vehicle.class, mappedBy = "user")
    @Valid
    @Expose
    @OrderBy("id desc")
    public List<Vehicle> vehicles = Lists.newArrayList();

    @Expose
    @OneToMany
    @JoinTable(name = "user_active_vehicle_map",
                joinColumns = {
                    @JoinColumn (name = "user_id")
                    },
                inverseJoinColumns = {
                    @JoinColumn(name = "vehicle_id")
                })
    @MapKeyColumn(name = "dtype")
    public Map<String, Vehicle> activeVehicles = new HashMap<String, Vehicle>();
}

车辆

@Entity
@org.hibernate.annotations.Entity(dynamicUpdate = true)
@Table(name = "pumps")
@TypeDefs({
    @TypeDef(name = "json", typeClass = JsonUserType.class)
})
abstract public class Vehicle extends Model
{

    @ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY, targetEntity = User.class)
    public User user;
}

0 个答案:

没有答案