java - 如何使用休眠中的条件转换mysql连接查询
问题描述
我想使用条件将下面的 MySql 查询转换为休眠。tbl_state 和 tbl_country 是我要加入的表,其中 tbl_state 和 tbl_country 有一个公共字段 country_id。
select s.*,c.country_name from tbl_state s,tbl_country c where
s.country_id=c.country_id ORDER BY s.state_name
+ order + " LIMIT " + pagesize + " OFFSET " + pagesize * pagenum;
解决方案
首先,您应该为表创建实体。我们假设 State 是 tbl_state 的实体, Country 是 tbl_country 的实体。
国家实体:
@Entity
@Table(name = "tbl_country")
public class Country {
private Integer countryId;
@Id
@Column(name="country_id")
public String getCountryId(){
return countryId;
}
}
国家实体:
@Entity
@Table(name = "tbl_state")
public class State {
private Integer stateId;
private String stateName;
private Country country;
@Id
@Column(name="state_id")
public String getStateId(){
return stateId;
}
@Column(name="state_name")
public String getStateName(){
return stateName;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="country_id")
public Country getCountry(){
return country;
}
}
标准代码:
Criteria stateCriteria = session.createCriteria(State.class);
Criteria countryCriteria = stateCriteria.createCriteria("country");
stateCriteria.addOrder(Order.desc("stateName"));
stateCriteria.setFirstResult(pagesize * pagenum);
stateCriteria.setMaxResults(pagesize);
List results = stateCriteria.list();
对于自定义结果,您应该创建一个 dto 类。例如 StateDto :
public class StateDto {
private String stateName;
private String countryName;
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}
然后你的标准代码可以像下面的代码。
Criteria stateCriteria = session.createCriteria(State.class);
Criteria countryCriteria = stateCriteria.createCriteria("country");
stateCriteria.addOrder(Order.desc("stateName"));
stateCriteria.setFirstResult(pagesize * pagenum);
stateCriteria.setMaxResults(pagesize);
stateCriteria.setProjection(Projections.projectionList()
.add(Projections.property("stateName").as("stateName"))
.add(Projections.property("country.name").as("countryName")));
List<StateDto> results = stateCriteria.list();
推荐阅读
- ethereum - 使用 geth --dev 的 gas * price + value 资金不足
- java - 如何检测 JavaFx 双击 listView
- javascript - 使用 jQuery 按 id 打开 html 元素
- visual-studio-code - 基于 monaco 编辑器的命名空间自动完成
- java - 想要从字符串数组中替换 WhiteSpace
- android - windowIsTranslucent 更改生命周期,但进入锁屏时出错
- gentoo - 台面标头之间出现冲突
- docker - How to dockerizing a spring boot app with one Dockerfile?
- c - 有没有办法在实际执行卸载之前“尝试卸载”?
- cookies - 如何在 ASP.NET Core 中设置永不过期的 cookie?