Ebean @ManyToOne,finder不检索相关对象的所有数据

我正在使用Ebean作为我的对象映射,而且我也是这样创建了我的SQL表

create table company ( id int auto_increment not null primary key, name varchar(100) ); create table employee ( id int auto_increment not null primary key, name varchar(100) not null, company_id int not null, constraint foreign key (company_id) references company (id) on delete restrict on update restrict ); 

这是Ebean公司的模式

 import javax.persistence.Entity; import javax.persistence.Id; import com.avaje.ebean.Model; @Entity public class Company extends Model { @Id public Integer id; public String name; } 

和员工模式

 @Entity public class Employee extends Model { @Id public Integer id; public String name; @ManyToOne public Company company; public static Finder<Long, Employee> find = new Finder<Long, Employee>(Long.class, Employee.class); } 

当我运行以下

 Company company = new Company(); company.name = "Microsoft"; company.save(); Employee employee = new Employee(); employee.name = "Mr John"; employee.company = company; employee.save(); Employee mrJohn = Employee.find.where().eq("id", 1).findUnique(); System.out.println(mrJohn.company.id); System.out.println(mrJohn.company.name); 

第一个System.out.println给出1(这是分配给员工的公司的正确的ID),但第二个显示空(我预期应该有“微软”值),输出是

 1 null 

因此,问题是为什么只检索公司模型的ID,而不是其他相关的数据?

  1. 您可以使用fetch()来热切地获取图形的其他部分。 在这种情况下,获取公司名称如下:

    Employee.find.fetch( “公司”, “名”),其中()EQ( “ID”,1).findUnique()。

  2. 总之,现场访问不能被拦截(除非你增强了调用者)。 所以对company.name使用字段访问意味着customer.name是一个GETFIELD操作,并且它没有被Ebean拦截,因此懒惰的加载没有被调用(因此返回null)。

更改为使用getter / setter意味着在调用customer.getName()时调用延迟加载。

Java不支持属性(从getter和setter开始)。 您可以查看其他像Groovy和Kotlin一样的JVM语言。

Groovy支持属性,使用Groovy的例子是@CompileStatic: https : //github.com/ebean-orm/avaje-ebeanorm-examples/blob/master/e-groovy https://github.com/ebean-orm/ avaje-ebeanorm-实例/斑点/主/电子常规/ SRC /主/常规/组织/示例/域/ Customer.groovy

Kotlin支持属性,例如: https : //github.com/ebean-orm/avaje-ebeanorm-examples/tree/master/e-kotlin-maven

干杯,罗伯。