1
votes

I'm trying to make some field readOnly -> insert and update aka save() should not send that field to DB but the field should be populated with select.

@ReadOnlyProperty from org.springframework.data.annotation.ReadOnlyProperty does not do the trick.

versions: spring-boot: 2.2.0.RC1, spring-data-jdbc: 1.1.0.RELEASE, spring-data-commons: 2.2.0.RELEASE

db: MSSQL

spring-data-jdbc readOnly

Should it work and is there any other way to do it?

NOTE: please don't mix spring-data-jdbc with spring-data-jpa

import java.util.Set;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.ReadOnlyProperty;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.MappedCollection;

public class Organization {
    @Id
    private Long id;
    private String name;
    @Column("readOnlyProperty")
    @ReadOnlyProperty
    private String readOnlyProperty;
    @ReadOnlyProperty
    @MappedCollection
    private Set<Employee> employees;
}
import org.springframework.data.annotation.Id;

public class Employee {
    @Id
    private Long id;
    private String name;
}
@Test
public void insert() {
    // insert should not set readOnlyProperty
    Organization organization = new Organization("org1", "readOnly");
    Employee employee = new Employee("emp1");
    Set<Employee> employess = new HashSet<>();
    employess.add(employee);
    organization.setEmployees(employess);
    organizationRepository.save(organization);
}

LOG: Executing prepared SQL statement [INSERT INTO organization (name, readOnlyProperty) VALUES (?, ?)]

Executing prepared SQL statement [INSERT INTO employee (name, organization) VALUES (?, ?)]

2
do you have an example project to look at? Or at least the code for your entity? - Jens Schauder
@JensSchauder code added. If it is necessary I will add project url - mpDeveloped

2 Answers

0
votes

This is a bug. I created DATAJDBC-431 for it and it will probably fixed in the next service release.

0
votes

I didn't test, but according to this

The Column annotation and XML element defines insertable and updatable options. These allow for this column, or foreign key field to be omitted from the SQL INSERT or UPDATE statement. These can be used if constraints on the table prevent insert or update operations. They can also be used if multiple attributes map to the same database column, such as with a foreign key field through a ManyToOne and Id or Basic mapping. Setting both insertable and updatable to false, effectively mark the attribute as read-only.

@Column(name="COLUMN_NAME",updatable=false, insertable=false)
private String fieldName;

should make the field read-only.