为了Old Gods and the New Gods,请不要这样做
这样做会完全弄乱您的数据库。你会迟早会遇到问题。查看您的个人资料,您获得了 CS 学位,因此您肯定参加过数据库课程。请记住 Second normal form 和 Third normal form 以及如果您的属性依赖于其他属性,您将如何打破它。
您应该做的是拥有一个临时字段(标有@Transient),或者您可以使用getter 并从那里提供信息。每次您需要访问 name_length 时,您都会调用此 getter,但不会将信息存储在数据库中。
即使您想在应用程序之外计算长度,您仍然可以为此使用一些数据库函数 - like length。
根据 OP 提到的要求进行编辑:
在 JPA 中,您可以通过两种方式声明列 - 在字段上或在方法(getter/setter)上。它会是这样的:
@Column(name = "complex_calculation") // Due to some bad requirement
public Integer getNameLength() {
return fisrtName.length() + lastName.length();
}
但是,您在问题中提到了 Ebean,并且 Ebean 不被视为参考 JPA 实现。很有可能还不支持此功能,但您可以在具体情况下尝试。
还有另一种被证明有效的方法。您可以这样定义模型:
@Entity
public class Person extends Model {
@Id
private Long id;
private String firstName;
private String lastName;
private Integer nameLength;
public Long getId() {
return id;
}
// getter for first name and last name with @Column annotation
@Column(name = "complex_calculation")
public Integer getNameLength() {
return firstName.length() + lastName.length();
}
public Person (String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
updateComplexCalculation();
}
public void setFirstName(String firstName) {
this.firstName = firstName;
updateComplexCalculation();
}
public void setLastName(String lastName) {
this.lastName = lastName;
updateComplexCalculation();
}
private void updateComplexCalculation() {
this.nameLength = firstName.length() + lastName.length();
}
}
重要的部分是updateComplexCalculation 方法。当构造函数被调用并且在每次 setter 调用时,您调用此方法来更新 complex 属性。当然,您应该只在计算所需的 setter 调用上调用它。
以下代码:
Person p = new Person("foo", "bar");
p.save();
Logger.debug("Complex calculation: " + p.getNameLength());
p.setFirstName("somethingElse");
p.save();
Logger.debug("Complex calculation: " + p.getNameLength());
然后产生:
[debug] application - Complex calculation: 6
[debug] application - Complex calculation: 16