如何将此 jdbc 查询转换为 JPA (JPQL)

How to translate this jdbc query to JPA (JPQL)

这是查询。我希望这足以简单地进行转换。我刚接触 JPA,特别是 JPQL,我们想转换这个查询。

select t1.field1, t1.field2, t1.field3 from TABLE_ONE t1, TABLE_TWO t2, TABLE_THREE t3 where t1.field2 = t2.field1 and t1.field3 = t3.field1 and t1.field1 = '123'

我已经开始创建实体对象...

@Entity
@Table(name="TABLE_ONE")
public class TableOne {
       @Column(name="field1")
       private String field1;

       @Column(name="field2")
       private String field2;

类 TableTwo 和 TableThree 相同。

如果您需要使用 @OneToMany@OneToOne 标记来翻译 JPQL 中的查询,我会感到困惑。我想仅仅为特定查询创建这些标签是不切实际的。顺便说一句,这是 JPA 2.0

感谢任何帮助。谢谢你。

根据 JPA 2.0 specification(第 11.1.6 节),您不需要对 class 类型的属性使用 @OneToMany@OneToOne 注释 String, 如:

The Basic annotation is the simplest type of mapping to a database column. The Basic annotation can be applied to a persistent property or instance variable of any of the following types: Java primitive types, wrappers of the primitive types, java.lang.String, ..., java.util.Date, java.util.Calendar, java.sql.Date, java.sql.Time, java.sql.Timestamp, byte[], Byte[], char[], Character[], enums, and any other type that implements Serializable.

As described in Section 2.8, the use of the Basic annotation is optional for persistent fields and properties of these types. If the Basic annotation is not specified for such a field or property, the default values of the Basic annotation will apply.

这是符合 JPA 的 ORM 实现所保证的行为。此外,当您使用 @Column 注释时,也会给出 String class 属性的持久性,但是,@Column 可用于影响数据库特定属性(例如,字段长度, name, nullable, etc...) 更明确的某个属性。

本机 JDBC 查询的翻译应该像这样适合您:

String jpqlConformQueryString = 
    "SELECT t1 from TableOne t1, TableTwo t2, TableThree t3 WHERE "+
    "t1.field2 = t2.field1 AND "+
    "t1.field3 = t3.field1 AND "+
    "t1.field1 = :field1";

// create a typed query to fetch only objects of that type
TypedQuery<TableOne> query = em.createQuery(jpqlConformQueryString, TableOne.class);

// set the value of the parameter "field1" to a value you choose...
query.setParameter("field1", "123");

// retrieve objects (transformed tuples) matching previously defined and parameterized query 
List<TableOne> result = query.getResultList();

// process the result list further 
// ...

这样,列表 "result" 将仅引用符合变量 jpqlConformQueryString 中指定的条件并受 t1.field1 的显式参数限制的对象。

请注意:您不必像在普通 JDBC 代码中那样 select 某些属性。相反,您 select 整个对象并使用每个对象的 getter/setter 方法来访问或操作已从数据库中读取的值。