I have an alert table which is transactional and an alert type table which is master. I would like to send out an email whenever an alert is added to the table, so I figured I would use PrePersist. However, in my email, I want to include some information that is included in the alert type table.
I have tried to add a reference to the AlertTypeRepository in the Alert class but I can't because my alert class is a @Table and alertTypeRepository is not a column.
Below is my Alert class
@Entity
@Table
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Alert {
@Id
@GeneratedValue
int id;
@Column
String name;
@Column
String alertTypeId;
@Column
String detailedMessage;
@Column
String status;
@Temporal(TemporalType.TIMESTAMP)
Date time;
}
Below is my AlertType class
@Entity
@Table
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class AlertType {
@Id
@GeneratedValue
int id;
@Column
String name;
@Column
String header;
@Column
String footer;
@Column
String summary;
@Column
String deliveryType;
@Column
Boolean active ;
@Column
String recipients;
}
I would like to have a PrePersist function inside of the Alert class. That allows me to access its corresponding header and footer from the AlertType class.
I figured out a solution so I hope this helps anyone facing a similar issue. Basically I had to create an EntityListener to the Alert class and then add the following class.
@Component
public class AlertListener {
static AlertTypeRepository alertTypeRepository;
@Autowired
public void init(AlertTypeRepository alertTypeRepository)
{
this.alertTypeRepository = alertTypeRepository;
}
@PrePersist
public void prePersist(Alert alert) {
List<AlertType> alertType= this.alertTypeRepository.findAll();
}
}
As I know the are two approaches to archive the purpose. Your alterType is not managed by Spring .
EntityListener
and apply it on your entity class, which does not seem to interest you. @Configurable
annotation: @Configurable(preConstruction = true)
class AlterType{
@Inject YourRepository bean as normal.
}
To make it work. Firstly you have to add aspectj
related jars into your project dependencies. Secondly you can choose load-time weaving or compile-time weaving to handling the injection for you class.
There is an example of aspectj compiler config in Maven can be used for compile-time weaving(note, just for aspectj compiler maven plugin config, I did not use @Configurable here.).
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.