在Spring + Hibernate中保存creationTimestamp和updatedTime,可以通过以下步骤实现:
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name = "your_table_name")
public class YourEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "creation_timestamp", nullable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date creationTimestamp;
@Column(name = "updated_time", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date updatedTime;
// 其他字段和方法...
// Getters and Setters...
}
<!-- 数据源配置 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="your_database_driver_class" />
<property name="url" value="your_database_url" />
<property name="username" value="your_database_username" />
<property name="password" value="your_database_password" />
</bean>
<!-- Hibernate SessionFactory 配置 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="your_entity_package" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">your_database_dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<!-- 其他Hibernate配置 -->
</props>
</property>
</bean>
<!-- Hibernate 事务管理器配置 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 开启事务注解支持 -->
<tx:annotation-driven transaction-manager="transactionManager" />
@Service
@Transactional
public class YourService {
@Autowired
private YourEntityDao yourEntityDao;
public void saveOrUpdate(YourEntity entity) {
if (entity.getId() == null) {
entity.setCreationTimestamp(new Date());
}
entity.setUpdatedTime(new Date());
yourEntityDao.saveOrUpdate(entity);
}
// 其他业务方法...
}
请注意,以上答案仅供参考,具体实现方式可能因项目需求和环境而异。
领取专属 10元无门槛券
手把手带您无忧上云