ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

如何在Jhipster生成的应用程序上从AbstractAuditingEntity扩展实体?

2019-07-02 16:47:44  阅读:533  来源: 互联网

标签:java spring-mvc hibernate testing jhipster


我用命令yo jhipster生成了一个实体:entity MyEntity(我用的是generator-jhipster@2.19.0)

以及以下选项

{
    "relationships": [],
    "fields": [
        {
            "fieldId": 1,
            "fieldName": "title",
            "fieldType": "String"
        }
    ],
    "changelogDate": "20150826154353",
    "dto": "no",
    "pagination": "no"
}

我在liquibase changelog文件中添加了可审计列

<changeSet id="20150826154353" author="jhipster">
    <createSequence sequenceName="SEQ_MYENTITY" startValue="1000" incrementBy="1"/>
    <createTable tableName="MYENTITY">
        <column name="id" type="bigint" autoIncrement="${autoIncrement}" defaultValueComputed="SEQ_MYENTITY.NEXTVAL">
            <constraints primaryKey="true" nullable="false"/>
        </column>
        <column name="title" type="varchar(255)"/>

        <!--auditable columns-->
        <column name="created_by" type="varchar(50)">
            <constraints nullable="false"/>
        </column>
        <column name="created_date" type="timestamp" defaultValueDate="${now}">
            <constraints nullable="false"/>
        </column>
        <column name="last_modified_by" type="varchar(50)"/>
        <column name="last_modified_date" type="timestamp"/>
    </createTable>

</changeSet>

并修改MyEntity类以扩展AbstractAuditingEntity

@Entity
@Table(name = "MYENTITY")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class MyEntity extends AbstractAuditingEntity implements Serializable {

然后运行mvn测试并获得以下异常

[DEBUG] com.example.web.rest.MyEntityResource - REST request to update MyEntity : MyEntity{id=2, title='UPDATED_TEXT'}

javax.validation.ConstraintViolationException: Validation failed for classes [com.example.domain.MyEntity] during update time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
    ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=createdBy, rootBeanClass=class com.example.domain.MyEntity, messageTemplate='{javax.validation.constraints.NotNull.message}'}
]
    at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:160)
    at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreUpdate(BeanValidationEventListener.java:103)
    at org.hibernate.action.internal.EntityUpdateAction.preUpdate(EntityUpdateAction.java:257)
    at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:134)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
    at org.hibernate.event.internal.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:67)
    at org.hibernate.internal.SessionImpl.autoFlushIfRequired(SessionImpl.java:1191)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1257)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
    at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:573)
    at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:449)
    at org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:67)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:318)

这是失败的考验

@Test
    @Transactional
    public void updateMyEntity() throws Exception {
        // Initialize the database
        myEntityRepository.saveAndFlush(myEntity);

        int databaseSizeBeforeUpdate = myEntityRepository.findAll().size();

        // Update the myEntity
        myEntity.setTitle(UPDATED_TITLE);


        restMyEntityMockMvc.perform(put("/api/myEntitys")
                .contentType(TestUtil.APPLICATION_JSON_UTF8)
                .content(TestUtil.convertObjectToJsonBytes(myEntity)))
                .andExpect(status().isOk());

        // Validate the MyEntity in the database
        List<MyEntity> myEntitys = myEntityRepository.findAll();
        assertThat(myEntitys).hasSize(databaseSizeBeforeUpdate);
        MyEntity testMyEntity = myEntitys.get(myEntitys.size() - 1);
        assertThat(testMyEntity.getTitle()).isEqualTo(UPDATED_TITLE);
    }

抛出异常的那条线就是这个

List<MyEntity> myEntitys = myEntityRepository.findAll();

我注意到TestUtil.convertObjectToJsonBytes(myEntity)方法正在返回没有可审计属性的JSON对象表示 – 由于@JsonIgnore注释而预期 – 但我认为mockMVC.perform更新操作不遵循updatable = false属性在createdBy字段上设置

@CreatedBy
@NotNull
@Column(name = "created_by", nullable = false, length = 50, updatable = false)
@JsonIgnore
private String createdBy;

我如何使实体可审计并通过测试?

解决方法:

问题是传输(序列化)对象不包括可审计属性(由于@JsonIgnore注释),这与@NotNull注释结合产生ConstraintViolation.

1.-一种解决方案是首先检索我们要更新的对象,然后仅更新您需要的字段.因此,在我们的示例中,我们需要修改MyEntityResource类的update方法,如下所示:

/**
 * PUT  /myEntitys -> Updates an existing myEntity.
 */
@RequestMapping(value = "/myEntitys",
    method = RequestMethod.PUT,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<MyEntity> update(@RequestBody MyEntity myEntityReceived) throws URISyntaxException {
    log.debug("REST request to update MyEntity : {}", myEntityReceived);
    if (myEntityReceived.getId() == null) {
        return create(myEntityReceived);
    }
    MyEntity myEntity = myEntityRepository.findOne(myEntityReceived.getId());
    myEntity.setTitle(myEntityReceived.getTitle());
    MyEntity result = myEntityRepository.save(myEntity);
    return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("myEntity", myEntity.getId().toString()))
            .body(result);
}

2.-另一种解决方案是通过从AbstractAuditingEntity中删除所需值的@JsonIgnore注释来包含可审计字段.

这将在创建实体时产生以下响应

{
"createdBy":"admin",
"createdDate":"2015-08-27T17:40:20Z",
"lastModifiedBy":"admin",
"lastModifiedDate":"2015-08-27T17:40:20Z",
"id":1,
"title":"New Entity"
}

因此,在更新实体时,请求将包含先前生成的值

{
"createdBy":"admin",
"createdDate":"2015-08-27T17:40:20Z",
"lastModifiedBy":"admin",
"lastModifiedDate":"2015-08-27T17:40:20Z",
"id":1,
"title":"New Entity Updated"
}

同样是更新响应,但更新了lastModified字段

{
"createdBy":"admin",
"createdDate":"2015-08-27T17:40:20Z",
"lastModifiedBy":"admin",
"lastModifiedDate":"2015-08-27T17:45:12Z",
"id":1,
"title":"New Entity Updated"
}

这两种解决方案都有自己的权衡,所以选择最适合你的方案.

另外,你应该在generator-jhipster上检查这个issue虽然它只标题为DTO实体,但是你是否使用它们也是同样的问题.

标签:java,spring-mvc,hibernate,testing,jhipster
来源: https://codeday.me/bug/20190702/1358288.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有