EntityManager.merge插入重复的实体

时间:2009-12-29 17:05:44

标签: java hibernate persistence sqlite entitymanager

我有一个非常特别的设置:我用Java创建所有类,在我的应用程序中连接它们(几个ManyToOne关系)。

然后,我想迭代我的对象并将它们保存到数据库中。有时,对象已经在数据库中,因此不应再次持久化。

我实现了hashCode()和equals() - 方法正确,但我的em.merge()仍然插入了对象。

再次:

我创建了一些对象,即我创建了一些玩家并设置了他们所在的团队。团队可能是Java中的不同对象,但根据他们的“等于”方法,它们是相同的。因此,如果我保存一个玩家,团队应该相应地保存(这是有效的),但如果团队存在于数据库中(根据equals-method),则不应再次插入,但应设置关系,当然。

我做错了什么?需要更多信息?

    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();
}

修改

@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);
    }
}

2 个答案:

答案 0 :(得分:4)

JPA使用@Id字段进行合并,它不会使用equals和hashCode方法来检查数据库中是否已存在实体。

在团队中添加@OneToMany映射,就像Bozho建议的那样,虽然我会这样做。

@OneToMany(cascade = { CascadeType.ALL })
private List<Player> players = new ArrayList<Player>();

public void addPlayer(Player player) {
    player.setTeam(this);
    players.add(player);
}

public Collection<Player> getPlayers() {
    return new ArrayList<Player>(this.players);
}

当你正在合并大量的entites时,我假设你正在从CSV或其他东西进行批量导入。然后,不是为CSV中的每一行创建一个新的团队/玩家,而是保持一个由名称键入的团队地图,并将玩家添加到相关团队。

所以,而不是

Team t = new Team();
t.setName(teamName)
Player p = new Player();
p.setName(playerName);
p.setTeam(t);

待办事项

Map<String, Team> teams = new HashMap<String,Team>();

...

if (!teams.containsKey(teamName)) {
    Team t = new Team();
    t.setDescription(teamName);
    teams.put(teamName, t)
}

Player p = new Player();
p.setName(p);
teams.get(teamName).addPlayer(p);

...

saveModels(teams.values());

答案 1 :(得分:0)

通过将Team类作为一个字段集合给玩家来尝试使关系双向。这将注释如此

@OneToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, targetEntity = Team.class)
Collection<Player> getPlayers() {
  return this.players;
}