加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 04:23:15 所属栏目:Java 来源:网络整理
导读:我正在使用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,compan
我正在使用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),但第二个显示为null(我预期应该具有值“Microsoft”),输出为

1
null

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

解决方法

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

Employee.find.fetch( “公司”,“名”),其中()EQ( “ID”,1).findUnique().
>简短的字段访问不能被截获(除非你增强了调用者).因此,对company.name使用字段访问意味着customer.name是一个GETFIELD操作,并且它没有被Ebean拦截,因此没有调用延迟加载(因此返回了null).

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

Java不支持属性(有getter和setter).您可以查看其他类似Groovy和Kotlin的JVM语言.

Groovy支持属性,使用带有@CompileStatic的Groovy的示例是:
https://github.com/ebean-orm/avaje-ebeanorm-examples/blob/master/e-groovy
https://github.com/ebean-orm/avaje-ebeanorm-examples/blob/master/e-groovy/src/main/groovy/org/example/domain/Customer.groovy

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

干杯,罗布.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读