|
34 | 34 | import org.grails.datastore.mapping.model.MappingContext; |
35 | 35 | import org.grails.datastore.mapping.model.PersistentEntity; |
36 | 36 | import org.grails.datastore.mapping.model.PersistentProperty; |
| 37 | +import org.springframework.beans.factory.annotation.Value; |
37 | 38 | import org.springframework.context.ApplicationEvent; |
38 | 39 |
|
39 | 40 | /** |
|
44 | 45 | */ |
45 | 46 | public class AutoTimestampEventListener extends AbstractPersistenceEventListener implements MappingContext.Listener { |
46 | 47 |
|
| 48 | + // if false, will not set timestamp on insert event if value is not null |
| 49 | + @Value("${grails.gorm.events.insertOverwrite:true}") |
| 50 | + boolean insertOverwrite = true; |
| 51 | + |
47 | 52 | public static final String DATE_CREATED_PROPERTY = "dateCreated"; |
48 | 53 | public static final String LAST_UPDATED_PROPERTY = "lastUpdated"; |
49 | 54 |
|
@@ -98,19 +103,23 @@ public boolean beforeInsert(PersistentEntity entity, EntityAccess ea) { |
98 | 103 | Set<String> props = getDateCreatedPropertyNames(name); |
99 | 104 | if (props != null) { |
100 | 105 | for (String prop : props) { |
101 | | - dateCreatedType = ea.getPropertyType(prop); |
102 | | - timestamp = timestampProvider.createTimestamp(dateCreatedType); |
103 | | - ea.setProperty(prop, timestamp); |
| 106 | + if (insertOverwrite || ea.getPropertyValue(prop) == null) { |
| 107 | + dateCreatedType = ea.getPropertyType(prop); |
| 108 | + timestamp = timestampProvider.createTimestamp(dateCreatedType); |
| 109 | + ea.setProperty(prop, timestamp); |
| 110 | + } |
104 | 111 | } |
105 | 112 | } |
106 | 113 | props = getLastUpdatedPropertyNames(name); |
107 | 114 | if (props != null) { |
108 | 115 | for (String prop : props) { |
109 | | - Class<?> lastUpdateType = ea.getPropertyType(prop); |
110 | | - if (dateCreatedType == null || !lastUpdateType.isAssignableFrom(dateCreatedType)) { |
111 | | - timestamp = timestampProvider.createTimestamp(lastUpdateType); |
| 116 | + if (insertOverwrite || ea.getPropertyValue(prop) == null) { |
| 117 | + Class<?> lastUpdateType = ea.getPropertyType(prop); |
| 118 | + if (dateCreatedType == null || !lastUpdateType.isAssignableFrom(dateCreatedType)) { |
| 119 | + timestamp = timestampProvider.createTimestamp(lastUpdateType); |
| 120 | + } |
| 121 | + ea.setProperty(prop, timestamp); |
112 | 122 | } |
113 | | - ea.setProperty(prop, timestamp); |
114 | 123 | } |
115 | 124 | } |
116 | 125 | return true; |
|
0 commit comments