简体   繁体   中英

Using @PrePersist and @PreUpdate with Ebean and Play 2.5.x not working?

I have strange issue that I can't understand why is this working while I was following simple documented way to do it, I have the following Entity:

@Entity
@Table(name = "users")
public class User extends Model {
    @Id
    @Column
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column
    @CreatedTimestamp
    private DateTime createdDate;

    @Column
    @UpdatedTimestamp
    private DateTime updatedDate;

    @Column
    @Version
    private long version = 0;

    @Column(length = 35, nullable = false)
    @Constraints.Required
    @Constraints.MinLength(2)
    @Constraints.MaxLength(50)
    private String firstName;

    @Column(length = 35, nullable = false)
    @Constraints.Required
    @Constraints.MinLength(2)
    @Constraints.MaxLength(50)
    private String lastName;

    @Column(length = 256)
    @Constraints.MaxLength(256)
    private String jobTitle;

    @Column(length = 1000)
    @JsonIgnore
    private String options;

    @Transient
    private Map<String, Object> properties = new HashMap<>();

    @PrePersist
    protected void prePersist() throws IOException {
        Logger.warn("PrePersist called");
    }

    @PreUpdate
    protected void preUpdate() throws IOException {
        Logger.warn("PreUpdate called");
    }

    @PostLoad
    private void postLoad() throws IOException {
        Logger.warn("PostLoad called");
    }
// settlers and getters here 

}

Then for new user, I call in controller or service:

User user = new User();
user.setFirstName("Someone").setLastName("Last Name"); // etc
//then 
user.insert();
// or you can even try 
// user.save();

I'm trying to save new user and update user, getting user the break point while debugging not call the methods that have @PrePersist , @PreUpdate and @PostLoad but they are not called at all, in real application I do some conversion from JSON string to Map options to properties and vice versa.

Supposed to be supported : http://ebean-orm.github.io/docs/features/eventlistening

I'm using play 2.5.6 and sbt-play-ebean 3.0.2 .

Well, I'm not sure is this a silly mistake or misunderstood, But the problem was the methods have wrong access modifiers.

They must be a public , not protected or private :

@PrePersist
public void prePersist() throws IOException {
    Logger.warn("PrePersist called");
}

@PreUpdate
public void preUpdate() throws IOException {
    Logger.warn("PreUpdate called");
}

@PostLoad
public void postLoad() throws IOException {
    Logger.warn("PostLoad called");
}

Edit: just in case, if @Transient column modified, @PreUpdate and PrePersist will not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM