gpt4 book ai didi

java - 如何更新ebean orm中的所有引用

转载 作者:行者123 更新时间:2023-11-30 02:54:05 25 4
gpt4 key购买 nike

我在更新 ebean 中的模型时遇到问题,但对该模型的其他引用没有更改。我想知道是否可以自动更新或刷新使用连接列或 @ManyToMany 映射引用更新模型的任何模型。

这是我的测试代码:

// Create students and club
Student john = new Student("John");
Student lizz = new Student("Lizz");
Club soccer = new Club("Soccer");

// Save the students
server.save(john);
server.save(lizz);

// Add them to their club
john.getClubs().add(soccer);
server.save(john);
lizz.getClubs().add(soccer);
server.save(lizz);

// Reload users (fresh)
john = server.find(Student.class).where().ieq("name", "john").findUnique();
lizz = server.find(Student.class).where().ieq("name", "lizz").findUnique();
System.out.println("Club: " + lizz.getClubs().get(0).getName());

// Modify the club name
john.getClubs().get(0).setName("Baseball");
System.out.println("Club: " + lizz.getClubs().get(0).getName());

// Update the club
server.save(john);
System.out.println("Club: " + lizz.getClubs().get(0).getName());

这些是我的模型:

@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true, updatable = false)
private int id;

@Column
private String name;

@ManyToMany(mappedBy = "students", cascade = CascadeType.ALL)
private List<Club> clubs;

@Version
private long version;
}

和:

@Entity
@Table(name = "clubs")
public class Club {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true, updatable = false)
private int id;

@Column
private String name;

@ManyToMany
@JoinColumn
private List<Student> students;

@Version
private long version;
}

输出是俱乐部仍然是足球,如下所示:
俱乐部:足球
俱乐部:足球
俱乐部:足球

最佳答案

您正在修改 John,但打印 Lizz。 Lizz 没有改变(因为 Lizz 的俱乐部已经加载并且没有刷新)。

原因是因为 John 和 Lizz 的获取位于 2 个不同的事务中,因此具有 2 个不同的持久性上下文。

如果存在跨越 John 和 Lizz 两者的获取的事务,则 Club 对于两者而言将是相同/单个实例,因为底层持久性上下文的范围仅限于该事务,并确保它们对 Club 使用相同的实例。

作为一个侧面,您应该考虑打开 SQL 和事务日志记录,以便确认它执行您认为应该执行的操作:

<!-- LOGBACK configuration -->

<!-- SQL and bind values -->
<logger name="org.avaje.ebean.SQL" level="TRACE"/>

<!-- Transaction Commit and Rollback events -->
<logger name="org.avaje.ebean.TXN" level="TRACE"/>

有关日志记录配置,请参阅 http://ebean-orm.github.io/docs/setup/logging

做:

server.beginTransaction();
try {
// persistence context scoped to transaction so
// .. now spans both fetches giving John and Lizz
// .. the same shared Club instance
john = server.find(Student.class).where().ieq("name", "john").findUnique();
lizz = server.find(Student.class).where().ieq("name", "lizz").findUnique();
} finally {
server.endTransaction();
}

关于java - 如何更新ebean orm中的所有引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37780890/

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