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

mrfwxfqh  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(35)

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

@Component
@Transactional
public class AuthenticationListener implements ApplicationListener<AuthenticationSuccessEvent> {

@Autowired
private UserRepository userRepository;

private final Logger logger = LoggerFactory.getLogger(this.getClass());

@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
    logger.info(userRepository.toString());
    String username = event.getAuthentication().getName();
    LoggedUser loggedUser = (LoggedUser) event.getAuthentication().getPrincipal();
    logger.info("Logged user: " + loggedUser);

    if (userRepository.existsByUsername(event.getAuthentication().getName())) {
        logger.info("Existing user: " + event.getAuthentication().getName());
        User user = userRepository.findByUsername(username);
        user.setFirstname(loggedUser.getFirstName());
        user.setLastname(loggedUser.getLastName());
        logger.info("Saved: " + userRepository.save(user).toString());
    } else {
        logger.info("Not existing user: " + event.getAuthentication().getName());
        User user = new User(loggedUser.getFirstName(), loggedUser.getLastName(), "", username);
        logger.info(user.toString());
        logger.info("Saved: " + userRepository.save(user).toString());
    }
  }
}

字符串
UserRepository.java:

@Repository
public interface UserRepository extends JpaRepository<User, Long>{

  List<User> findAll();

  List<User> findByFirstname(String firstname);
  List<User> findByLastname(String lastname);
  List<User> findByFirstnameAndLastnameAndEmail(String firstname, String lastname, String email);

  User findByEmail(String email);   
  User findByUsername(String username);

  @Query("SELECT CASE WHEN COUNT(u) > 0 THEN true ELSE false END FROM User u WHERE u.email = :email")
  boolean existsByEmail(@Param("email") String email);

  @Query("SELECT CASE WHEN COUNT(u) > 0 THEN true ELSE false END FROM User u WHERE u.username = :username")
  boolean existsByUsername(@Param("username") String username);

}


编辑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]
10:58:52.404 [http-nio-8080-exec-4] DEBUG org.hibernate.loader.Loader - Result set row: 0
10:58:52.405 [http-nio-8080-exec-4] DEBUG org.hibernate.loader.Loader - Result row: 
10:58:52.978 [http-nio-8080-exec-4] DEBUG o.s.o.jpa.EntityManagerFactoryUtils - Closing JPA EntityManager
10:58:52.979 [http-nio-8080-exec-4] DEBUG o.s.o.h.HibernateTransactionManager - Initiating transaction commit
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])]
10:58:52.980 [http-nio-8080-exec-4] DEBUG o.h.e.t.internal.TransactionImpl - committing
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
10:59:03.767 [http-nio-8080-exec-4] INFO  a.p.a.shared.AuthenticationListener - Not existing user: bob
10:59:05.754 [http-nio-8080-exec-4] INFO  a.p.a.shared.AuthenticationListener -  Firstname: Bob | Lastname: Hamilton | E-Mail: 
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; ''
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; ''
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
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])]
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]
10:59:12.932 [http-nio-8080-exec-4] DEBUG o.h.e.t.internal.TransactionImpl - begin
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]
10:59:17.963 [http-nio-8080-exec-4] DEBUG o.s.o.jpa.EntityManagerFactoryUtils - Opening JPA EntityManager
10:59:17.964 [http-nio-8080-exec-4] DEBUG o.s.o.jpa.EntityManagerFactoryUtils - Registering transaction synchronization for JPA EntityManager
10:59:26.892 [http-nio-8080-exec-4] DEBUG o.s.o.jpa.EntityManagerFactoryUtils - Closing JPA EntityManager
10:59:26.898 [http-nio-8080-exec-4] DEBUG o.s.o.h.HibernateTransactionManager - Initiating transaction commit
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])]
10:59:26.899 [http-nio-8080-exec-4] DEBUG o.h.e.t.internal.TransactionImpl - committing
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(添加用户实体):

@Entity
@Table(name = "user")
@JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "USER_ID")

private long userId;
@NotNull
@Size(min = 1, max = 50)
@Column(name = "USER_FIRSTNAME")
private String firstname;

@NotNull
@Size(min = 1, max = 50)
@Column(name = "USER_LASTNAME")
private String lastname;

@NotNull
@Size(min = 1, max = 150)
@Column(name = "USER_USERNAME")
private String username;

@NotNull
@Size(min = 0, max = 150)
@Column(name = "USER_EMAIL")
private String email;

@Column(name = "USER_ACTIVE", nullable = false)
private boolean active;

@Autowired
@OneToMany(mappedBy = "user")
@JsonBackReference
private List<Ownership> ownerships;

public User() {
}

public User(long userId) {
    this.userId = userId;
}

public User(String firstname, String lastname, String email, String username) {
    this.firstname = firstname;
    this.lastname = lastname;
    this.email = email;
    this.username = username;
    this.active = true;
}

public User(String firstname, String lastname, String email) {
    this.firstname = firstname;
    this.lastname = lastname;
    this.email = email;
    this.active = true;
}


public long getId() {
    return userId;
}

public void setId(long Id) {
    this.userId = Id;
}

public String getFirstname() {
    return firstname;
}

public void setFirstname(String firstname) {
    this.firstname = firstname;
}

public String getLastname() {
    return lastname;
}

public void setLastname(String lastname) {
    this.lastname = lastname;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public boolean isActive() {
    return active;
}

public void setActive(boolean active) {
    this.active = active;
}

public List<Ownership> getOwnerships() {
    return ownerships;
}

public void setOwnerships(List<Ownership> ownerships) {
    this.ownerships = ownerships;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

@Override
public String toString() {
    return " Firstname: " + firstname + " | Lastname: " + lastname + " | E-Mail: " + email;
}

}

wyyhbhjk

wyyhbhjk1#

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

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

字符串

相关问题