Hi all,
I've got a pretty special setup: I create all the classes in Java, connect them in my application (several ManyToOne-relationships).
Then, I'd like to iterate over my objects and save them into the database. Sometimes, an object is already in the database, then it should not be persisted again.
I implemented the hashCode() and equals()-method correct, but my em.merge() inserts the objects nevertheless.
Again:
I create some objects, i.e. I create some player and set in which team they are. the teams may be different objects in Java, but according to their "equals"-method, they are the same. So if I save a player, the team should be saved accordingly (that works), but if the team exists in the database (according to the equals-method), it should not be inserted again, but the relationship should be set, of course.
What I'm I doing wrong? More information needed?
private static void saveModels(final Set<?> models) {
EntityManagerFactory factory = null;
factory = Persistence.createEntityManagerFactory("sqlite");
EntityManager manager = factory.createEntityManager();
manager.getTransaction().begin();
for (Object object : models) {
manager.merge(object);
}
manager.getTransaction().commit();
manager.close();
factory.close();
}
edit
@Entity
public class Team {
private long id;
private String description;
@Id
@GeneratedValue
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description= description;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + description.length();
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Team other = (Team) obj;
if (!description.equals(other.getDescription())) {
return false;
}
return true;
}
}
@Entity
public class Player {
private long id;
private Team team;
private String name;
@Id
@GeneratedValue
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, targetEntity = Team.class)
@JoinColumn(name = "team_id")
public Team getTeam() {
return team;
}
public void setTeam(Team team) {
this.team = team;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
return name.length();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Player)) {
return false;
}
Player other = (Player) obj;
return other.getName().equals(name);
}
}