我在Spring Boot中创建了一个简单的应用程序。我的方法删除有问题。
我这样创建一个UserController: @Controller 公共类UserController {
@Autowired
UserRepository userRepository;
@RequestMapping(value = "/students", method = RequestMethod.GET)
public String tables(Model model){
model.addAttribute("users", userRepository.findAll());
return "students";
}
@RequestMapping(value = "/delete/{id}", method = GET)
public String delete(Model model, @PathVariable("id") Long id){
User user = userRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Niepoprawne id : " + id));
userRepository.deleteUserById(id);
model.addAttribute("students", userRepository.findAll());
return "redirect:/students";
}}
在我的UserPrepository中,我有这种方法:
@Repository
public interface UserRepository extends JpaRepository<User,Long> {
User findByEmail(String email);
List<User> findAll();
void deleteUserById(Long id);
}
UserService:
@Service
public interface UserService extends UserDetailsService {
User findByEmail(String email);
User save(UserRegistrationDto registration);
List<User> findAll();
void deleteUserById(Long id);
}
和UserServiceImpl:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
@Autowired
private BCryptPasswordEncoder passwordEncoder;
public User findByEmail(String email){
return userRepository.findByEmail(email);
}
private Collection<? extends GrantedAuthority> mapRolesToAuthorities(Collection<Role> roles){
return roles.stream()
.map(role -> new SimpleGrantedAuthority(role.getName()))
.collect(Collectors.toList());
}
public List<User> findAll(){
return userRepository.findAll();
}
public void deleteUserById(Long id) {
userRepository.deleteUserById(id);
}
}
在前端,我创建一个像这样的简单表:
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0" >
<thead>
<tr>
<th>IMIE</th>
<th>NAZWISKO</th>
<th>EMAIL</th>
<th>AKCJA</th>
</tr>
</thead>
<tbody>
<tr>
<tr th:each="user :${users}">
<td th:text="${user.firstName}"></td>
<td th:text="${user.lastName}"></td>
<td th:text="${user.email}"></td>
<td>
<!--<a th:href="${'/students/delete/' + user.id}" class="btn btn-danger">Usuń</a>-->
<td><a th:href="@{/delete/{id}(id=${user.id})}">Delete</a></td>
</td>
</tr>
</tr>
</tbody>
</table>
现在,当我启动我的应用程序并单击“删除”按钮时,我在网站上遇到此错误:没有EntityManager,可用于当前线程的实际交易-无法可靠地处理“删除”调用;嵌套的异常是javax.persistence.TransactionRequiredException:没有用于当前线程的具有实际事务的EntityManager-无法可靠地处理“删除”调用
什么不是我的?如何解决?
答案 0 :(得分:1)
默认情况下,只有CRUD方法(CrudRepository方法)被标记为事务性的。如果您使用的是自定义查询方法,则应使用@Transactional
注释对其进行显式标记。
因此将@Transactional放在如下所示的存储库类中的deleteUserById方法上。
@Transactional
void deleteUserById(Long id);
引用this
答案 1 :(得分:1)
或者您也可以使用CrudRepository deleteUserById
的默认方法替换void deleteById(ID id)
,从而删除具有给定ID的实体。