robm robm - 2 months ago 11
Java Question

How do I use update using hibernate where i am not sure on which field is to be altered?

public User updateUser(User user) {

try {
User result = session.get(User.class, user.getId());
if (result == null) {
throw new FilamentNoSuchRecordException(new CoreError(304, "User does not exist"));
}
session.clear();
session.update(user);

return user;
} catch (HibernateException e) {
e.printStackTrace();
}
throw new FilamentDataConnectivityException(new CoreError(305,"Connectivity issue. Please see System Administrator"));
}


customer model is as follows

@Entity
@Table(name = "customers")
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
@DynamicUpdate(value=true)
@SelectBeforeUpdate(value=true)
@SQLDelete(sql="Update customers SET deleted = true where customer_id=?")
@Where(clause="deleted != true")
@ApiModel(description="Create or update Customers")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Customer {

@Id
@Column(name="customer_id")
@NotNull
@GeneratedValue(strategy=GenerationType.AUTO)
private int id = 0;

@Column(name="name")
@ApiModelProperty(value="The name of the customer", example="Mr J. Bond")
@NotNull
private String name;

@Column(name="description")
@ApiModelProperty(value="Desciption of the customer")
@NotNull
private String description;

@Column(name="logo_url")
@ApiModelProperty(value="Logo of user")
@NotNull
private String logo;

@Column(name="created_at")
@ApiModelProperty(value="The date the item was created", example="")
@NotNull
private Date createdAt;

@Column(name="updated_at")
@ApiModelProperty(value="The date the item was updated", example="")
@NotNull
private Date updatedAt;

@ApiModelProperty(hidden=true)
@OneToMany(fetch = FetchType.LAZY, mappedBy = "customer")
private Set<Application> applications = new HashSet<Application>();

@ManyToMany(mappedBy = "customers")
private Set<Service> services = new HashSet<Service>();

@ApiModelProperty(hidden=true)
@OneToMany(fetch = FetchType.LAZY, mappedBy = "customer")
private Set<User> users = new HashSet<User>();

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(
name = "customer_subscription",
joinColumns = @JoinColumn(name = "customer_id"),
inverseJoinColumns = @JoinColumn(name = "subscription_id")
)
private Set<Subscription> subscriptions = new HashSet<Subscription>();

@ApiModelProperty(hidden=true)
@OneToMany(fetch = FetchType.LAZY, mappedBy = "customer")
private Set<Corpus> corpus = new HashSet<Corpus>();

@Column(name="deleted")
@NotNull
private boolean deleteFlag;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Set<Application> getApplications() {
return applications;
}

public void setApplications(Set<Application> applications) {
this.applications = applications;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public String getLogo() {
return logo;
}

public void setLogo(String logo) {
this.logo = logo;
}

public Date getCreatedAt() {
return createdAt;
}

public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}

public Date getUpdatedAt() {
return updatedAt;
}

public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}

public Set<Service> getServices() {
return services;
}

public void setServices(Set<Service> services) {
this.services = services;
}

public Set<User> getUsers() {
return users;
}

public void setUsers(Set<User> users) {
this.users = users;
}

public Set<Corpus> getCorpus() {
return corpus;
}

public void setCorpus(Set<Corpus> corpus) {
this.corpus = corpus;
}

public Set<Subscription> getSubscriptions() {
return subscriptions;
}

public void setSubscriptions(Set<Subscription> subscriptions) {
this.subscriptions = subscriptions;
}

public boolean getDeleteFlag() {
return deleteFlag;
}

public void setDeleteFlag(boolean deleteFlag) {
this.deleteFlag = deleteFlag;
}


}

I check whether the object exists within the database, then update with an object, for example all fields could be null apart from the ID and the one thats needs to be updated. All fields are set to @NotNull in the model and I am using the @DynamicUpdate(value=true) and @SelectBeforeUpdate(value=true) annotations, but these seem to do nothing.

Just get failure saying the null fields can not be null. How do I update the row?

Answer

As we discussed in above comments, try this -

public User updateUser(User user) {

    try {
        User result = session.get(User.class, user.getId());
        if (result == null) {
            throw new FilamentNoSuchRecordException(new CoreError(304, "User does not exist"));
        }
        result.setName(user.getName()); // update some properties
        session.update(result); // you should update 'result', not 'user'

        return result;
    } catch (HibernateException e) {
        e.printStackTrace();
        throw new FilamentDataConnectivityException(new CoreError(305,"Connectivity issue. Please see System Administrator"));
    }

}