与JPA一起加入:我应该编写哪些查询来获得与JDBC相同的结果?

时间:2017-09-11 21:07:16

标签: java postgresql jpa jdbc

我是JPA的新手,我试图将我在JDBC中使用的方法转换为JPA作为练习。 这应该计算我数据库中所有恒星的所有质量并更新相对质量列。为了计算质量,我需要恒星的温度和350um波段的通量值。问题是我将这些数据保存在我的数据库的不同表中,因此我必须使用JOIN。

JDBC APPROACH

public void updateAllMasses() {
    String selectQuery = "SELECT s.starid, s.temperature, f.value" +
            " FROM star s JOIN flux f " +
            "ON s.starid = f.source " +
            "WHERE f.band = 350.00 AND f.value != 0";
    try {
        ResultSet resultSet = databaseUtilJDBC.dbExecuteQuery(selectQuery);
        while (resultSet.next()) {
            String starId = resultSet.getString("starid");
            Double flux350 = resultSet.getDouble("value");
            Double temp = resultSet.getDouble("temperature");
            if (temp != 0) {
                String updateQuery = "UPDATE star " +
                        "SET mass = 0.053 * " + flux350 + " * (100) * (EXP(41.14 / " + temp + " ) - 1) "
                        + "WHERE starid = '" + starId + "';";
                databaseUtilJDBC.dbExecuteUpdate(updateQuery);
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

JPA APPROACH ATTEMPT

在这里,我需要以某种方式在JOIN对象和Star对象之间建立Flux

这是Star课程的草稿。

@Entity
@Table(name = "star")
public class Star implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Column(name = "starid", nullable = false)
    private String starId;
    @Column(name = "temperature")
    private BigDecimal temperature;
    @Column(name = "mass")
    private BigDecimal mass;

    // With all constructors, getters and setters

}

这是我用于通量的实体类:

@Entity
@Table(name = "flux")
public class Flux implements Serializable {

    private static final long serialVersionUID = 1L;

    @EmbeddedId private FluxId fluxId = new FluxId();
    @Column(name = "value")
    private BigDecimal value;

    // With constructors, getters and setters

}

使用其idclass:

@Embeddable
public class FluxId implements Serializable {
    private static final long serialVersionUID = 1L;
    @Column(name = "source", nullable = false)
    private String source;
    @Column(name = "band", nullable = false)
    private BigDecimal band;

    // With constructors, getters and setters

}

这是我最终尝试使用JPA:

public void updateAllMasses() {
    String query = "???"; // Query to get all values I need
    List list = databaseUtilJPA.dbExecuteQuery(query);
    for (Object aList : list) {
        Star star = (Star) aList; // Here I would just get a Star object... while I would need also it's flux value at 350 band!
        if (!star.getTemperature().equals(BigDecimal.valueOf(0))) {
            query = "UPDATE Star star SET star.mass = 0.053 * flux.value * 100 * (EXP(41.14 / star.temperature) - 1)" +
                    " WHERE star.starId = '" + star.getStarId() + "'";
            databaseUtilJPA.dbExecuteUpdate(query);
        }
    }
}

我应该写什么问题?

2 个答案:

答案 0 :(得分:1)

您的模型未正确映射。如果要使用JPA的连接,则必须正确声明它们。您的FLuxId必须如下所示:

@Embeddable
public class FluxId implements Serializable {

  @ManyToOne
  @JoinColumn(name="source")
  private Star star;

  @Column(name = "band", nullable = false)
  private BigDecimal band;

  // With constructors, getters and setters

}

然后将Flux类标记为具有单独的IdClass:

@Entity
@IdClass(FluxId.class)
public class Flux {         

  @Id
  private Source source;

  @Id
  private BigDecimal band;

 // With constructors, getters and setters

}

警告必须为它实现一个正确的equals()方法,以确保持久化后的对象与其自身相同在从数据库中检索时是相同的。

确保它看起来像这样:

  @Override
  public boolean equals(Object obj) {

    if (obj == this) return true;       

    if (obj == null || !(obj.getClass().equals(this.getClass())))
        return false;

    FluxID otherFluxId = (FluxID)obj;

    if (this.getSource() == null
            || otherFluxId.getSource() == null
            || this.getBand() == null
            || otherFluxId.getBand() == null)
        return false;

    return this.getSource().equals(otherFluxId.getSource()) && 
           this.getBand().equals(otherFluxId.getBand());
}

@Override
public int hashCode() {

    if (this.getSource() == null && this.getBand() == null) return super.hashCode();

    return (this.getSource() != null ? this.getSource().hashCode() : 0 ) ^
           (this.getBand() != null ? this.getBand().hashCode() : 0 );

}

请注意,这个实现有一个缺陷,即hashCode()在持久化之前与持久化之后不同。我不知道如何避免这种情况,但如果您将实体存储在某个集合中,则必须小心谨慎。

完成所有这些后,您的查询将变为:

SELECT f.source.id, f.source.temperature, f.value
FROM Flux f
WHERE f.band = 350.00 AND f.value != 0

如果您想要对象,您也可以使用该对象:

SELECT f.source
FROM Flux f
WHERE f.band = 350.00 AND f.value != 0

(不是100%肯定最后一句的语法。)

答案 1 :(得分:0)

JPA也支持本机JDBC查询。

但是,如果您之间存在one-to-many关系,则可以使用注释在jpaStar类或两者中使用注释定义{<1}}。

Flux

那么你的查询可以:

@Entity
public class Star {
    @OneToMany
    private List<Flux> fluxes = new ArrayList<>();
}

@Entity
public class Flux {
    @ManyToOne
    private Star star;
}