首页 > 解决方案 > 如何使用休眠中的条件转换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;

标签: javamysqlspringhibernate

解决方案


首先,您应该为表创建实体。我们假设 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();

推荐阅读