java - 如何删除 spring-data-jpa 中位于多个侧面的项目?
问题描述
部门和员工之间存在双向的一对多关系。
@Setter
@Getter
@Entity
@Table(name = "t_department")
public class Department {
@Id
private String id;
private String name;
@OneToMany(mappedBy = "department",fetch = FetchType.EAGER,cascade = CascadeType.ALL)
private List<Employee> employees;
}
@Setter
@Getter
@Entity
@Table(name = "t_employee")
public class Employee {
@Id
private String id;
private String name;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "dept_id")
private Department department;
}
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, String> {
}
在数据库中,我有这些记录。
t_department:
+----+------------+
| id | name |
+----+------------+
| 2 | accounting |
| 3 | logistics |
+----+------------+
t_employee:
+----+------+---------+
| id | name | dept_id |
+----+------+---------+
| 3 | Tom | 2 |
| 4 | Tina | 3 |
+----+------+---------+
当我试图删除一个 Employee(id="3") 时,
@Test
@Transactional
public void should_delete_employee_success_when_delete_employee_given_a_exist_employee_id_in_DB() {
employeeRepository.delete("3");
}
但在控制台中,它只打印了 2 个选择语句而没有删除:
Hibernate: select employee0_.id as id1_2_0_, employee0_.dept_id as dept_id3_2_0_, employee0_.name as name2_2_0_, department1_.id as id1_1_1_, department1_.name as name2_1_1_ from t_employee employee0_ left outer join t_department department1_ on employee0_.dept_id=department1_.id where employee0_.id=?
Hibernate: select employees0_.dept_id as dept_id3_2_0_, employees0_.id as id1_2_0_, employees0_.id as id1_2_1_, employees0_.dept_id as dept_id3_2_1_, employees0_.name as name2_2_1_ from t_employee employees0_ where employees0_.dept_id=?
我去看了数据库,什么都没做。
spring-data-jpa 是如何工作的?我迷茫了好几天。
提前感谢您的回答。
解决方案
因为@Transactional
Spring 测试默认标记为仅回滚,并且 SQL 更改通常仅在事务提交时刷新到数据库。
然后,您将需要 (1) 手动刷新更改以强制写入数据库:
public class SomeTest{
@PersistenceContext
private EntityManager em;
@Test
@Transactional
public void should_delete_employee_success_when_delete_employee_given_a_exist_employee_id_in_DB() {
employeeRepository.delete("3");
em.flush(); //force db update however transaction will still be rolled back
}
或 (2)
将事务设置为不是仅用于回滚,您可以通过各种方式执行此操作,包括使用@Commit
和@Rollback
注释:
推荐阅读
- hazelcast - Hazelcast 是否在 jmx 中无限期地持有锁?
- web-component - 在 Web 组件中不使用保留的公共名称的正确方法是什么
- swift - MLMediaLibrary - 显示照片库 - Swift 代码错误 - macOS
- function - 在 Dataweave 1.0 中创建全局函数
- flutter - Flutter 在搜索框中使用 REST API 从 JSON 中检索数据
- sql - 将一列排序/拆分为一行中的不同视图列
- php - laravel 没有从第一次设置会话数据
- unity3d - 修复使用 ARCore 在按钮上创建的地面上的家具
- node.js - 使用 pm2 启动时 Mongoose 中的只读属性分配错误
- jsf - 如何将 CASBIN 与 JSF 集成