java.sql.SQLSyntaxErrorException: No such column: id
当表已包含列id
时
我正在尝试让以下原生SQL查询与来自Repository类的MariaDB SQL中的预期结果一起运行:
SELECT name
FROM table1 t1
WHERE t1.table2_id IN (
SELECT id
FROM table2 t2
WHERE t2.column1_number = 1 AND
t2.id IS NOT NULL
)
ORDER BY t1.name
实体类如下:
@Entity
@Table(name = "table1")
public class Table1 {
@Column(nullable = false)
private String name;
@Column(nullable = false)
private Integer number;
@ManyToOne
@JoinColumn(name = "table2_id")
private Table2 table2;
// Getters and Setters
}
@Entity
@Table(name="table2")
public class Table2 {
private Integer id;
private Integer column1_number;
@Override
public Integer getId() {
return id;
}
@Override
public void setId(Integer id) {
this.id = id;
}
// Getters and Setters
}
存储库是:
@Repository
public interface Table1Repository extends JpaRepository<Table1, Integer> {
@Query(value = "SELECT name FROM table1 t1 WHERE t1.table2_id IN (SELECT id FROM table2 t2 WHERE t2.column1_number = ?1 AND t2.id IS NOT NULL) ORDER BY t1.name", nativeQuery = true)
List<Table1> findByNumberOrderByName(Integer number);
}
你知道为什么我在运行时会出现这个错误吗?编译时不会发生此错误。
发布于 2019-05-11 16:03:08
@Query(value = "SELECT name FROM table1 t1 WHERE t1.table2_id IN (SELECT id FROM table2 t2 WHERE t2.column1_number = ?1 AND t2.id IS NOT NULL) ORDER BY t1.name", nativeQuery = true)
List<Table1> findByNumberOrderByName(Integer number);
应该是List<String>
而不是List<Table1>
所以解决方案是:
@Query(value = "SELECT name FROM table1 t1 WHERE t1.table2_id IN (SELECT id FROM table2 t2 WHERE t2.column1_number = ?1 AND t2.id IS NOT NULL) ORDER BY t1.name", nativeQuery = true)
List<String> findByNumberOrderByName(Integer number);
发布于 2019-05-11 14:30:45
尝试将Id元素添加到table1中,并使用@Id注释对两个表的Id字段进行注释,如下所示。
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
https://stackoverflow.com/questions/56086620
复制相似问题