Reputation: 43
I need to invoke custom annotation implementation , But my implementation is not getting called. In the
below code snippet ,I have a Profile Object with two fields (id , content). Content field accept a string and
need to change the content at runtime via a custom annotation.
My domain object
@Entity
@Table(name = "profile", catalog = "db")
public class Profile implements java.io.Serializable{
private Integer profileId;
@ProcessContent(convertor = ProcessContent.class)
private String content;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "PROFILE_ID", unique = true, nullable = false)
public Integer getProfileId() {
return profileId;
}
public void setProfileId(Integer profileId) {
this.profileId = profileId;
}
@Column(name = "CONTENT", unique = true, nullable = false, length = 255)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
My custom annotation
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ProcessContent {
@SuppressWarnings("rawtypes")
Class<? extends Object> convertor() default DefaultFieldValueConvertor.class;
}
Sample Annotation implementation. (Please note that this is a sample and complex logic comes here)
public class DefaultFieldValueConvertor {
public Object convert(Object value) {
return (value + "Processed");
}
}
Tester
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Profile profile = new Profile();
profile.setContent("OOOOOOOOOPSSSSSSSSS");
session.save(profile);
session.getTransaction().commit();
session.close();
}
Question - > I can see the passing string getting save in DB instead the one processed via my annotation implementation.
Upvotes: 1
Views: 1403
Reputation: 61558
In order to execute code on JPA lifecycle events like loading, merging, refreshing etc, you can use JPA lifecycle listeners. You can define listener callback methods inside your entity or in an own class. If you use the callback in a single entity type, listener methods is the easy way. Use listener classes when you need a certain type of operation to be performed on different entity types.
If you want to manipulate data before storing it, you can combine the @PreUpdate and the @PrePersist callbacks.
@PreUpdate
@PrePersist
public void convert() {
content += "Processed";
}
Upvotes: 1