spring Sping Boot Hibernate加载但不保存来自事件日志的数据

mrfwxfqh  于 2024-01-05  发布在  Spring
关注(0)|答案(1)|浏览(101)

我在从事件侦听器内部保存数据时遇到问题。
目前我正在侦听AuthenticationEvent,并且该事件正在按预期调用(使用记录器检查)。
我希望能够在事件中使用JPA存储库,并在事件被触发时保存数据。
仓库正在初始化,数据从数据库加载,只有userRepository.save()不起作用。我在保存过程中也没有得到任何异常。保存()方法在其他RestController中工作没有任何问题。
(数据库为MySQL)
这是实现ApplicationServer接口的侦听器类:

  1. @Component
  2. @Transactional
  3. public class AuthenticationListener implements ApplicationListener<AuthenticationSuccessEvent> {
  4. @Autowired
  5. private UserRepository userRepository;
  6. private final Logger logger = LoggerFactory.getLogger(this.getClass());
  7. @Override
  8. public void onApplicationEvent(AuthenticationSuccessEvent event) {
  9. logger.info(userRepository.toString());
  10. String username = event.getAuthentication().getName();
  11. LoggedUser loggedUser = (LoggedUser) event.getAuthentication().getPrincipal();
  12. logger.info("Logged user: " + loggedUser);
  13. if (userRepository.existsByUsername(event.getAuthentication().getName())) {
  14. logger.info("Existing user: " + event.getAuthentication().getName());
  15. User user = userRepository.findByUsername(username);
  16. user.setFirstname(loggedUser.getFirstName());
  17. user.setLastname(loggedUser.getLastName());
  18. logger.info("Saved: " + userRepository.save(user).toString());
  19. } else {
  20. logger.info("Not existing user: " + event.getAuthentication().getName());
  21. User user = new User(loggedUser.getFirstName(), loggedUser.getLastName(), "", username);
  22. logger.info(user.toString());
  23. logger.info("Saved: " + userRepository.save(user).toString());
  24. }
  25. }
  26. }

字符串
UserRepository.java:

  1. @Repository
  2. public interface UserRepository extends JpaRepository<User, Long>{
  3. List<User> findAll();
  4. List<User> findByFirstname(String firstname);
  5. List<User> findByLastname(String lastname);
  6. List<User> findByFirstnameAndLastnameAndEmail(String firstname, String lastname, String email);
  7. User findByEmail(String email);
  8. User findByUsername(String username);
  9. @Query("SELECT CASE WHEN COUNT(u) > 0 THEN true ELSE false END FROM User u WHERE u.email = :email")
  10. boolean existsByEmail(@Param("email") String email);
  11. @Query("SELECT CASE WHEN COUNT(u) > 0 THEN true ELSE false END FROM User u WHERE u.username = :username")
  12. boolean existsByUsername(@Param("username") String username);
  13. }


编辑1(在保存点附近添加日志):

  1. 10:58:52.351 [http-nio-8080-exec-4] DEBUG o.s.j.d.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/airpng]
  2. 10:58:52.404 [http-nio-8080-exec-4] DEBUG org.hibernate.loader.Loader - Result set row: 0
  3. 10:58:52.405 [http-nio-8080-exec-4] DEBUG org.hibernate.loader.Loader - Result row:
  4. 10:58:52.978 [http-nio-8080-exec-4] DEBUG o.s.o.jpa.EntityManagerFactoryUtils - Closing JPA EntityManager
  5. 10:58:52.979 [http-nio-8080-exec-4] DEBUG o.s.o.h.HibernateTransactionManager - Initiating transaction commit
  6. 10:58:52.979 [http-nio-8080-exec-4] DEBUG o.s.o.h.HibernateTransactionManager - Committing Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
  7. 10:58:52.980 [http-nio-8080-exec-4] DEBUG o.h.e.t.internal.TransactionImpl - committing
  8. 10:58:52.982 [http-nio-8080-exec-4] DEBUG o.s.o.h.HibernateTransactionManager - Closing Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] after transaction
  9. 10:59:03.767 [http-nio-8080-exec-4] INFO a.p.a.shared.AuthenticationListener - Not existing user: bob
  10. 10:59:05.754 [http-nio-8080-exec-4] INFO a.p.a.shared.AuthenticationListener - Firstname: Bob | Lastname: Hamilton | E-Mail:
  11. 10:59:07.172 [http-nio-8080-exec-4] DEBUG o.s.d.r.c.s.TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource - Adding transactional method 'save' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
  12. 10:59:12.915 [http-nio-8080-exec-4] DEBUG o.s.o.h.HibernateTransactionManager - Creating new transaction with name [org.springframework.data.jpa.repository.support.SimpleJpaRepository.save]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
  13. 10:59:12.916 [http-nio-8080-exec-4] DEBUG o.s.o.h.HibernateTransactionManager - Opened new Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for Hibernate transaction
  14. 10:59:12.916 [http-nio-8080-exec-4] DEBUG o.s.o.h.HibernateTransactionManager - Preparing JDBC Connection of Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
  15. 10:59:12.916 [http-nio-8080-exec-4] DEBUG o.s.j.d.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/airpng]
  16. 10:59:12.932 [http-nio-8080-exec-4] DEBUG o.h.e.t.internal.TransactionImpl - begin
  17. 10:59:12.933 [http-nio-8080-exec-4] DEBUG o.s.o.h.HibernateTransactionManager - Exposing Hibernate transaction as JDBC transaction [com.mysql.jdbc.JDBC4Connection@38ba8070]
  18. 10:59:17.963 [http-nio-8080-exec-4] DEBUG o.s.o.jpa.EntityManagerFactoryUtils - Opening JPA EntityManager
  19. 10:59:17.964 [http-nio-8080-exec-4] DEBUG o.s.o.jpa.EntityManagerFactoryUtils - Registering transaction synchronization for JPA EntityManager
  20. 10:59:26.892 [http-nio-8080-exec-4] DEBUG o.s.o.jpa.EntityManagerFactoryUtils - Closing JPA EntityManager
  21. 10:59:26.898 [http-nio-8080-exec-4] DEBUG o.s.o.h.HibernateTransactionManager - Initiating transaction commit
  22. 10:59:26.898 [http-nio-8080-exec-4] DEBUG o.s.o.h.HibernateTransactionManager - Committing Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
  23. 10:59:26.899 [http-nio-8080-exec-4] DEBUG o.h.e.t.internal.TransactionImpl - committing
  24. 10:59:26.900 [http-nio-8080-exec-4] DEBUG o.s.o.h.HibernateTransactionManager - Closing Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] after transaction


编辑2(添加用户实体):

  1. @Entity
  2. @Table(name = "user")
  3. @JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
  4. public class User {
  5. @Id
  6. @GeneratedValue(strategy = GenerationType.IDENTITY)
  7. @Column(name = "USER_ID")
  8. private long userId;
  9. @NotNull
  10. @Size(min = 1, max = 50)
  11. @Column(name = "USER_FIRSTNAME")
  12. private String firstname;
  13. @NotNull
  14. @Size(min = 1, max = 50)
  15. @Column(name = "USER_LASTNAME")
  16. private String lastname;
  17. @NotNull
  18. @Size(min = 1, max = 150)
  19. @Column(name = "USER_USERNAME")
  20. private String username;
  21. @NotNull
  22. @Size(min = 0, max = 150)
  23. @Column(name = "USER_EMAIL")
  24. private String email;
  25. @Column(name = "USER_ACTIVE", nullable = false)
  26. private boolean active;
  27. @Autowired
  28. @OneToMany(mappedBy = "user")
  29. @JsonBackReference
  30. private List<Ownership> ownerships;
  31. public User() {
  32. }
  33. public User(long userId) {
  34. this.userId = userId;
  35. }
  36. public User(String firstname, String lastname, String email, String username) {
  37. this.firstname = firstname;
  38. this.lastname = lastname;
  39. this.email = email;
  40. this.username = username;
  41. this.active = true;
  42. }
  43. public User(String firstname, String lastname, String email) {
  44. this.firstname = firstname;
  45. this.lastname = lastname;
  46. this.email = email;
  47. this.active = true;
  48. }
  49. public long getId() {
  50. return userId;
  51. }
  52. public void setId(long Id) {
  53. this.userId = Id;
  54. }
  55. public String getFirstname() {
  56. return firstname;
  57. }
  58. public void setFirstname(String firstname) {
  59. this.firstname = firstname;
  60. }
  61. public String getLastname() {
  62. return lastname;
  63. }
  64. public void setLastname(String lastname) {
  65. this.lastname = lastname;
  66. }
  67. public String getEmail() {
  68. return email;
  69. }
  70. public void setEmail(String email) {
  71. this.email = email;
  72. }
  73. public boolean isActive() {
  74. return active;
  75. }
  76. public void setActive(boolean active) {
  77. this.active = active;
  78. }
  79. public List<Ownership> getOwnerships() {
  80. return ownerships;
  81. }
  82. public void setOwnerships(List<Ownership> ownerships) {
  83. this.ownerships = ownerships;
  84. }
  85. public String getUsername() {
  86. return username;
  87. }
  88. public void setUsername(String username) {
  89. this.username = username;
  90. }
  91. @Override
  92. public String toString() {
  93. return " Firstname: " + firstname + " | Lastname: " + lastname + " | E-Mail: " + email;
  94. }
  95. }

wyyhbhjk

wyyhbhjk1#

问题在于事件侦听器在不同的线程中运行,并且看起来它需要一个显式的事务来保存实体。

  1. Just annotate your method with @Transactional(propagation = Propagation.REQUIRES_NEW)

字符串

相关问题