如何在休眠状态下使用条件转换mysql联接查询

时间:2019-03-19 09:14:18

标签: java mysql spring hibernate

我想使用条件将下面的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;

1 个答案:

答案 0 :(得分:0)

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