服务类
@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中。
但是如果我通过两种方式传递同一个对象 一个) 在控制器
Table1 t1 = new Table1()
... setters
Table1 t2 = t1
tableService.saveTable1(t1,10,t2)
b)中 表1 t1 =新表1() tableService.saveTable1(t1,10,T1)
这两种方法只是在DB中创建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;
}
}
答案 0 :(得分:0)
TL; DR - 在同一会话中,同一对象不能持续两次。
语句Table1 t2 = t1;
基本上使tableService.saveTable1(t1,10,t2)
与tableService.saveTable1(t1,10,t1)
相同。因此,只有一条记录被保留,因为在同一会话中使用相同的对象引用。
由于通过new
关键字创建的两个对象具有不同的引用,因此在DB中保存相应的两个记录。
两次持续存在同一个对象
另请注意,建议您覆盖实体的equals
和hashCode
以避免任何意外。