gpt4 book ai didi

java - Hibernate CreateCriteria 用于依赖类

转载 作者:行者123 更新时间:2023-12-02 10:19:12 25 4
gpt4 key购买 nike

我正在开发一个应用程序,我必须在其中显示有关车辆详细信息的数据/信息。我有 2 个表 makemodel,其中 make_idmodel 表中的外键。我有 2 个实体类 MakeModel 如下所示:

@Entity
@Table(name = "make")
@PrimaryKeyJoinColumn(name="make_id")
public class Make {
@Id
@Column(name = "make_id")
private String makeId;

@Column(name = "make_name")
private String makeName;

@ManyToOne
@JoinColumn(name = "mfg_unit_id")
private MfgUnit mfgUnit;

// Getter and Setters
}


@Entity
@Table(name = "model")
public class Model {
@Id
@Column(name = "model_id")
private String modelId;

@Column(name = "model_creation_date")
private Date modelCreationDate;

@Column(name = "make_id")
private long makeId;

@ManyToOne
@JoinColumn(name = "make_id")
private Make make;

// Getter and Setters
}

我能够检索所有 Make,但我的要求是仅检索 model_creation_date 之间的 Make今天和过去 30 天。任何人都可以帮助我如何为此建立 Hibernate 标准吗?

最佳答案

可能还有另一种解决方案,但要实现此目的,您需要修改 Make 类,如下所示,引入与 Model 类的新关系(@OneToMany):

@Entity
@Table(name = "make")
@PrimaryKeyJoinColumn(name="make_id")
public class Make {
@Id
@Column(name = "make_id")
private String makeId;

@Column(name = "make_name")
private String makeName;

// ** introduced new relationship **
@OneToMany(mappedBy="make", fetch = FetchType.LAZY)
private List<Model> models;

@ManyToOne
@JoinColumn(name = "mfg_unit_id")
private MfgUnit mfgUnit;

// Getter and Setters
}

并保持“Model”类不变:

@Entity
@Table(name = "model")
public class Model {
@Id
@Column(name = "model_id")
private String modelId;

// change the datatype as Date or similar Datatype
@Column(name = "model_creation_date")
private Date modelCreationDate;

@Column(name = "make_id")
private long makeId;

@ManyToOne
@JoinColumn(name = "make_id")
private Make make;

// Getter and Setters
}

一旦您与“Make”中的“Model”建立了关系,您就可以执行以下代码来获取结果:

Calendar cal = Calendar.getInstance();
// today
Date toDate=cal.getTime();
cal.add( Calendar.DATE, -30 );
//date before 30 days
Date fromDate=cal.getTime();


Criteria criteria = session.createCriteria(Make.class , "m")
.createAlias("models", "s")
.add(Restrictions.between("s.modelCreationDate", fromDate, toDate))
// if the above condition dosen't give you exact result you may try following(2)
// try gt or lt ... as needed
//.add(Restrictions.ge("publicationDate", fromDate))
//.add(Restrictions.le("publicationDate", fromDate))
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

List<Make> ll2 = criteria.list();

关于java - Hibernate CreateCriteria 用于依赖类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54460319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com