弹簧数据 JPA 插入数



Service Class

@Service
public class TableService {
    @Autowired
    private Table1Repo t1Repo;
    public void saveTable1(Table1 t,int a, Table1 t2){
        t1Repo.save(t);
        int x = 10/a; 
        t1Repo.save(t2);
    }
}

现在在控制器中,当我传递 Table1 的两个不同对象(均使用 new 创建(时,这两行插入到 DB 中。

但是如果我通过两种方式传递同一个对象a) 在控制器中

 Table1 t1 = new Table1()
 ... setters
 Table1 t2 = t1
 tableService.saveTable1(t1,10,t2)

b( 表 1 t1 = 新的表 1(( tableService.saveTable1(t1,10,t1(

这两种方法只是在数据库中创建 1 行?这是为什么?

表1 实体

@Entity
@Table(name="table1")
public class Table1 implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    private int id;
    private String name;
    public Table1() {
    }
    public int getId() {
        return this.id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

TL;DR - 同一对象不能在同一会话中持久化两次。

语句Table1 t2 = t1;实质上使tableService.saveTable1(t1,10,t2)tableService.saveTable1(t1,10,t1)相同。因此,由于在同一会话中使用相同的对象引用,因此仅保留一条记录。

由于通过关键字创建的两个对象具有不同的引用new因此在数据库中保存相应的两条记录。

对于将同一对象保留两次

  • 将它们保存在不同的会话中(可能很棘手(
  • 深度克隆原始对象
  • 并在同一会话中保存原始对象和克隆对象(推荐(

另外,请注意,建议覆盖实体的equalshashCode以避免任何意外。

最新更新