Java Spring Boot休眠加载但不保存事件侦听器中的数据

Java Spring Boot休眠加载但不保存事件侦听器中的数据,java,spring,hibernate,spring-boot,spring-data-jpa,Java,Spring,Hibernate,Spring Boot,Spring Data Jpa,从事件侦听器内部保存数据时出现问题 目前,我正在侦听AuthenticationSuccessEvent,事件正在按预期调用(使用记录器检查) 我希望能够在事件中使用JPA存储库,并在触发事件时保存数据 正在初始化存储库,从数据库加载数据,但只有userRepository.save()无效。在保存期间,我也不会得到任何异常。 save()方法在其他RestController中工作,没有任何问题 (使用的数据库是MySQL) 这是实现ApplicationListener接口的侦听器类: @C

从事件侦听器内部保存数据时出现问题

目前,我正在侦听AuthenticationSuccessEvent,事件正在按预期调用(使用记录器检查)

我希望能够在事件中使用JPA存储库,并在触发事件时保存数据

正在初始化存储库,从数据库加载数据,但只有userRepository.save()无效。在保存期间,我也不会得到任何异常。 save()方法在其他RestController中工作,没有任何问题

(使用的数据库是MySQL)

这是实现ApplicationListener接口的侦听器类:

@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());
    }
  }
}
编辑2(已添加用户实体):

@实体
@表(name=“user”)
@JsonIgnoreProperties({“HibernateLazInitializer”,“handler”})
公共类用户{
@身份证
@GeneratedValue(策略=GenerationType.IDENTITY)
@列(name=“USER\u ID”)
私有长用户ID;
@NotNull
@尺寸(最小值=1,最大值=50)
@列(name=“USER\u FIRSTNAME”)
私有字符串名;
@NotNull
@尺寸(最小值=1,最大值=50)
@列(name=“USER\u LASTNAME”)
私有字符串lastname;
@NotNull
@尺寸(最小值=1,最大值=150)
@列(name=“USER\u USERNAME”)
私有字符串用户名;
@NotNull
@尺寸(最小值=0,最大值=150)
@列(name=“USER\u EMAIL”)
私人字符串电子邮件;
@列(name=“USER\u ACTIVE”,null=false)
私有布尔活动;
@自动连线
@OneToMany(mappedBy=“用户”)
@JsonBackReference
私有所有权清单;
公共用户(){
}
公共用户(长用户ID){
this.userId=userId;
}
公共用户(字符串名、字符串名、字符串电子邮件、字符串用户名){
this.firstname=firstname;
this.lastname=lastname;
this.email=电子邮件;
this.username=用户名;
this.active=true;
}
公共用户(stringfirstname、stringlastname、stringemail){
this.firstname=firstname;
this.lastname=lastname;
this.email=电子邮件;
this.active=true;
}
公共长getId(){
返回用户标识;
}
公共无效集合Id(长Id){
this.userId=Id;
}
公共字符串getFirstname(){
返回名字;
}
public void setFirstname(字符串firstname){
this.firstname=firstname;
}
公共字符串getLastname(){
返回姓氏;
}
public void setLastname(字符串lastname){
this.lastname=lastname;
}
公共字符串getEmail(){
回复邮件;
}
公用电子邮件(字符串电子邮件){
this.email=电子邮件;
}
公共布尔isActive(){
主动返回;
}
public void setActive(布尔激活){
这个.active=active;
}
公共列表getOwnerships(){
归还所有权;
}
公共所有权(列出所有权){
this.ownerships=所有权;
}
公共字符串getUsername(){
返回用户名;
}
public void setUsername(字符串用户名){
this.username=用户名;
}
@凌驾
公共字符串toString(){
返回“Firstname:+Firstname+”| Lastname:+Lastname+| E-Mail:+email;
}
}

您可以打开org.springframework和org.hibernate的日志记录并在保存点附近发布日志吗?您好,这里是日志(编辑1)您可以发布用户实体源代码吗?从调试行看,Hibernate似乎认为它没有什么要保存的。也许您的实体映射错误,不允许Hibernate计算出需要添加的行?这有用吗?我在原始帖子中发布了用户实体,我相信如果映射错误,那么保存在任何地方都不会起作用,但在restcontroller@R.Kozlica你找到这个问题的解决办法了吗?我也面临同样的问题。你能打开org.springframework和org.hibernate的日志记录并在保存点附近发布你的日志吗?嗨,这里是日志(编辑1)你能发布你的用户实体源代码吗?从调试行看,Hibernate似乎认为它没有什么要保存的。也许您的实体映射错误,不允许Hibernate计算出需要添加的行?这有用吗?我在原始帖子中发布了用户实体,我相信如果映射错误,那么保存在任何地方都不会起作用,但在restcontroller@R.Kozlica你找到这个问题的解决办法了吗?我也面临同样的问题。
@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);

}
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
@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;
}

}