Hi,
if the object was loaded before with the same session, I can avoid this problem with s.contains(item). (s == org.hibernate.Session)
Hibernate.isInitialized() may help if it was loaded outside the current session. But I'm not sure about this.
If the object wasn't loaded at all before, but is still in the database. I could try to load it before.
But there I'm facing two problems:
1) I normally don't expose the ID and I want to use a general function with Object as Argument, so I can't use
"Object get(Class clazz, Serializable id)" , cause of the lack of the id.
getIdentifier(Object object) works only if the object was loaded by Hibernate before.
A way around this problem would be to expose the ID by using an interface which would replace the Object as argument for my function, but this isn't my preferred solution at the moment. Cause it makes it possible to manipulate the id accidentally.
Ok, I could avoid this by returning new instances with thegiven value, instead of returning the id-object. (setID is not provided.) But is this good practice?
But this may be the only one and the effort isn't too big.
Also I have a compound naturally key, which I would have to generate for the above solution.
Code:
@Embeddable
public class LaendermodellPK implements Serializable {
@Enumerated(value = EnumType.STRING)
private KnownCountries name;
@Basic
private int year;
@Enumerated(value = EnumType.STRING)
private Variations type;
@Lob
private String comment;
private LaendermodellPK() {
}
@Override
public boolean equals(final Object obj) {
....
}
@Override
public int hashCode() {
...
}
}
Code:
@Entity
@IdClass(LaendermodellPK.class)
public class Laendermodell implements Comparable<Laendermodell> {
@Version
@Column(name = "VERSION_OPTLOCK")
@SuppressWarnings("unused")
private long version;
@Enumerated(value = EnumType.STRING)
@Id
private KnownCountries name;
@Id
private int year;
@Enumerated(value = EnumType.STRING)
@Id
private Variations type;
@Id
@Lob
private String comment;
...
}
So I would have to add an new constructor and implement an method like this
Code:
LaendermodellPK(final KnownCountries name, final int year, final Variations type, final String comment) {
this.name = name;
this.year = year;
this.type = type;
this.comment = comment;
}
Code:
public interface SupportsDatabaseID {
public Serializable getId();
}
Code:
public Serializable getId() {
return new LaendermodellPK(this.name, this.year, this.type, this.comment);
}
Is this good pratice?
2) How could I check for difference between the two objects behind equals and key identity?
In other words: is the current object dirty?
So I can decide If I have to ask the user or not.
I don't want to do this by hand, but I haven't found an appropriate function yet. I don't want to update the data in any case, so megre, update and saveOrUpdate aren't helpful here.
Thanks a lot.
Greetings Michael