gpt4 book ai didi

java - Spring Data删除功能不删除记录

转载 作者:行者123 更新时间:2023-12-02 08:23:33 25 4
gpt4 key购买 nike

我有以下简单的应用程序

用户实体

@Entity
public class Users implements Serializable {

@Id
@GeneratedValue
private long id;

private String name;

@OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade = {CascadeType.ALL})
private Set<UserRoleUser> userRoleUser;

// GETTERS AND SETTERS
}

UserRole 实体

@Entity
public class UserRole implements Serializable {

@Id
@GeneratedValue
private long id;

private String roleName;

@OneToMany(mappedBy = "userrole", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<UserRoleUser> userRoleUser;

// GETTERS AND SETTERS
}

UserRoleUser 多对多解析器类

@Entity
public class UserRoleUser implements Serializable {

@Id
@GeneratedValue
private long id;

@ManyToOne
@JoinColumn(name = "fk_userId")
private Users user;

@ManyToOne
@JoinColumn(name = "fk_userroleId")
private UserRole userrole;

// GETTERS AND SETTERS
}

UserRoleUserRepository

@Repository
@Transactional
public interface UserRoleUserRepository extends JpaRepository<UserRoleUser, Long>, QueryDslPredicateExecutor<UserRoleUser>{

}

Application

@SpringBootApplication
@Configuration
public class Application {

public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);

UserRoleUserRepository userRoleUserRepository = context.getBean(UserRoleUserRepository.class);

Iterable<UserRoleUser> findAll = userRoleUserRepository.findAll(QUserRoleUser.userRoleUser.id.gt(0));

for (UserRoleUser userRoleUser : findAll) {
userRoleUserRepository.delete(userRoleUser);
}

}

}

运行main应用程序时,UserRoleUser表中的数据库记录不会被删除。可能是什么问题?我正在使用 Spring Data 和 QueryDsl。

我也尝试过将删除功能放在 Controller 上,但仍然不起作用。

@RestController
@RequestMapping("/api")
public class DeleteController {

@Autowired
UserRoleUserRepository userRoleUserRepository;

@GetMapping("/delete")
public String delete() {
Iterable<UserRoleUser> findAll = userRoleUserRepository.findAll(QUserRoleUser.userRoleUser.id.gt(0));

for (UserRoleUser userRoleUser : findAll) {
userRoleUserRepository.delete(userRoleUser);
}

return new Date().toString();
}
}

最佳答案

如果您需要使用CrudRepository提供的给定方法,请使用JpaRepository.deleteInBatch()。这样问题就解决了。

关于java - Spring Data删除功能不删除记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48398783/

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