我正在尝试使某些字段只读->插入和更新又名save()不应将该字段发送到数据库,但该字段应填充select。
来自 org.springframework.data.annotation.ReadOnlyProperty 的@ReadOnlyProperty不能解决问题。
版本: spring-boot:2.2.0.RC1,spring-data-jdbc:1.1.0.RELEASE,spring-data-commons:2.2.0.RELEASE
数据库: MSSQL
它应该工作吗?还有其他方法吗?
注意:请不要将 spring-data-jdbc 与 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: 执行准备好的 SQL 语句 [INSERT INTO organization (name, readOnlyProperty) VALUES (?, ?)]
执行准备好的 SQL 语句 [INSERT INTO employee (name, organization) VALUES (?, ?)]