membersound
membersound

Reputation: 86747

How to make a JPA Column insertable only during JUnit tests?

@Entity
public class MyEntity {
    @Column(insertable = false,
            updatable = true,
            columnDefinition = "TIMESTAMP default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP")
    private LocalDateTime modification;
}

In general, the timestamp should be managed by mysql only, not by the application using the entity. Thus insertable=false.

But during a junit itest, I want to forcibly change the modification timestamp to a fixed value. Which would only be possible if insertable=true.

Question: is it possible to change the attribute only during testing?

Upvotes: 0

Views: 614

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36163

You could create a orm.xml in the test/resources/META-INF directory and override the mapping with XML.

The tags in the XML are the same as the annotations but instead of camel-case in kebab-case.

Please find the whole spec here: http://www.datanucleus.org/products/accessplatform/jpa/metadata_xml.html

@Gimby is right the orm.xml is additive so you can just override what you need:

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings version="2.1"
                 xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm">

    <package>your package here</package>

    <entity class="MyEntity">
        <attributes>
            <basic name="modification">
                <column insertable="true" />
            </basic>
        </attributes>
    </entity>

</entity-mappings>

Upvotes: 2

Related Questions