gpt4 book ai didi

java - 将对象从对象 A 添加到对象 B 而不创建新对象? hibernate

转载 作者:行者123 更新时间:2023-11-30 06:39:09 25 4
gpt4 key购买 nike

假设我有两个对象,一个是用户对象,另一个是状态对象。状态对象基本上是美国的 50 个州,因此无需更改。然而,用户对象具有用户曾经所处的状态的集合。像这样:

@Entity
@Table(name="tbl_users")
class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id", unique=true, nullable = false)
private int id;

@Column(name="user_name")
private String name;

@OneToMany(targetEntity=State.class, orphanRemoval = false)
@Column(name="states")
private Collection<State> states;

//getters and setters
}

States 实体如下所示:

@Entity
@Table(name="tbl_states")
class State {

@Id
@Column(name="id", unique=true, nullable=false)
private int id;

@Column(name="state")
private String state;

// getters and setters
}

添加用户的代码(使用 hibernate ):

public int addUser(User user) {
em.persist(user);
em.flush();
return user.getId();
}

通过id获取状态的代码:

public State getStateById(int id) {
return em.createQuery("SELECT s FROM State s WHERE s.id =:id, State.class)
.setParameter("id", id)
.getSingleResult();
}

但是当我尝试创建用户并选择多个状态时,我收到 PSQLException:

org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "uk_g6pr701i2pcq7400xrlb0hns"
2017-06-21T22:54:35.959991+00:00 app[web.1]: Detail: Key (states_id)=(5) already exists.

我尝试查找 Cascade 方法,看看是否可以使用任何方法,但 Cascade.MERGE 和 Cascade.PERSIST 似乎做了同样的事情,其余的我认为我不需要(REMOVE、DETACH 等) 。我的问题是:如何向 User 对象添加状态而不出现该错误?

最佳答案

此代码有效:

class Example {

@Test
public void workingTest() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("testPU");
EntityManager em = emf.createEntityManager();

// Creating three states
State alabama = new State(state: 'Alabama');
State louisiana = new State(state: 'Louisiana');
State texas = new State(state: 'Texas');
em.getTransaction().begin();
em.persist(alabama);
em.persist(louisiana);
em.persist(texas);
em.getTransaction().commit();

List<State> states = em.createQuery('FROM State').getResultList();

// Assert only three states on DB
assert states.size() == 3;

User userFromAlabama = new User();
User userFromAlabamaAndTexas = new User();

em.getTransaction().begin();
State alabamaFromDB = em.find(State, alabama.getId());
State texasFromDB = em.find(State, texas.getId());
userFromAlabama.getStates().add(alabamaFromDB);
userFromAlabamaAndTexas.getStates().add(alabamaFromDB);
userFromAlabamaAndTexas.getStates().add(texasFromDB);

em.persist(userFromAlabama);
em.persist(userFromAlabamaAndTexas);
em.getTransaction().commit();

states = em.createQuery('FROM State').getResultList();

// Assert only three states on DB again
assert states.size() == 3;

// Assert one user
User userFromDB = em.find(User, userFromAlabama.getId());
assert userFromDB.getStates().size() == 1;

userFromDB = em.find(User, userFromAlabamaAndTexas.getId());
assert userFromDB.getStates().size() == 2;
}
}

@Entity
@Table(name="tbl_users")
class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id

@Column(name="user_name")
private String name

@ManyToMany
private Collection<State> states = Lists.newArrayList()

// Getters and setters
}

@Entity
@Table(name="tbl_states")
class State {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

@Column(name="state")
private String state;
// Getters and setters
}

您应该将映射更改为@ManyToMany!

数据库上必须有 3 个表,如下所示:TBL_USERS、TBL_STATES 和 TBL_USERS_TBL_STATES

TBL_USERS_TBL_STATES 表是 Hibernate 在使用 @ManyToMany 注释属性时使用的默认表名称。如果要更改 TBL_USERS_TBL_STATES 的表名,也可以使用 @JoinTable 注释。请参阅文档 here

使用此配置,您应该能够从数据库获取状态,将其添加到新用户,然后保留它。我做了一个单元测试,它有效!

关于java - 将对象从对象 A 添加到对象 B 而不创建新对象? hibernate ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44701667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com