我正在开发一个必须显示有关车辆详细信息的数据/信息的应用程序。我有2个表make
和model
,其中make_id
是model
表中的外键。我有2个实体类Make
和Model
,如下所示:
@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
,但是我的要求是仅检索Make
在今天和过去30天之间的model_creation_date
。有人可以帮助我如何建立休眠标准吗?
答案 0 :(得分:1)
可能还有另一种解决方案,但是要实现此目的,您需要修改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
}
一旦与“制作”中的“模型”建立了关系,就可以执行以下代码来获取结果:
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();
答案 1 :(得分:0)
对不起,我不知道为什么将日期声明为字符串:
私有字符串 modelCreationDate;
无论如何,我假定您将modelCreationDate声明为Date / LocalDate或类似的Type。我尚未测试代码,但希望以下代码可以解决您的问题。祝你好运!
SELECT COUNT(*) FROM parent WHERE Date1 <= DATEADD(DAY, -3, GETDATE())
答案 2 :(得分:0)
除了user3169715's answer之外,我还可以使用查询来检索记录
Calendar cal = Calendar.getInstance();
Date toDate = cal.getTime();
cal.add(Calendar.DATE, -30);
Date fromDate = cal.getTime();
String hql = "SELECT make FROM Model m where m.modelCreationDate between :from_date and :to_date";
Query query = session.createQuery(hql);
query.setParameter("from_date", fromDate);
query.setParameter("to_date", toDate);
List results = query.list(); // Result list