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);
}
关于为什么在运行时出现此错误的任何想法?在编译时不会发生此错误。
答案 0 :(得分:1)
@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);
答案 1 :(得分:0)
您正在尝试使用id在table2中进行搜索,但是您没有从table1中选择正确的映射列,该列应为 table2_id.id ,因此查询应类似于
SELECT name FROM table1 t1 WHERE t1.table2_id.id IN (SELECT id FROM table2 t2 WHERE t2.column1_number = 1 AND t2.id IS NOT NULL) ORDER BY t1.name
还要注意您正在使用本机查询,这意味着直接查询数据库,因此请确保在数据库表中使用相同的正确名称。
答案 2 :(得分:0)
尝试向表1中添加Id元素,并使用如下所示的@Id注释对两个表ID字段进行注释。
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;