springboot之JpaRepository查询列名错误

记录一次报错。

在数据库查询中,对实体类使用JpaRepository,如用户表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
-- 用户表
CREATE TABLE IF NOT EXISTS USER
(id INT UNSIGNED AUTO_INCREMENT,
userName VARCHAR(20) NOT NULL,
passWord VARCHAR(32) NOT NULL,
sex VARCHAR(4) NOT NULL,
phone VARCHAR(32),
email VARCHAR(32),
employer VARCHAR(32),
remarks VARCHAR(1000),
PRIMARY KEY (id)
)ENGINE=INNODB DEFAULT CHARSET=utf8;

//user类
public class User {
@Id
@Column
private String id;
@Column
private String userName;
@Column
private String passWord;
@Column
private String sex;
@Column
private String phone;
@Column
private String email;
@Column
private String employer;
@Column
private String remarks;
。。。。
}

//数据库交互类
import com.example.springboot.bean.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface UserMapper extends JpaRepository<User,String> {
User findUserByUsername(String username);
Page<User> findAll(Pageable pageable);
List<User> findAll();
}

此时在调用查找时会报错如下:

1
2
3
java.sql.SQLSyntaxErrorException: Unknown column 'subwaycoun0_.pass_num1' in 'field list'
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.18.jar:8.0.18]

原因:主要就是数据库和实体类名称不匹配,造成不匹配的原因为数据库字段时驼峰命名的userName执行的时候他会给你的查询字段名称改为user_Name

解决办法1:将数据库中的驼峰命名法改为下划线,即:userName -> user_name

Donate comment here