I have searched through various GPT and CSDN articles, but I haven't found the correct solution. It is commonly mentioned that the issue is related to the XML file location...
Error Code#
- User Class
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("user")
public class User {
@TableField("user_id")
private Long userId; // User ID
@TableField("user_name")
private String userName; // Username
@TableField("user_password")
private String userPassword; // User password
@TableField("user_authority")
private Integer userAuthority; // User authority
}
- Mapper Interface
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
- Test Method
@SpringBootTest
public class UserTest {
@Autowired
private UserMapper userMapper;
// Select user by id
@Test
public void testSelectById() {
User user = userMapper.selectById(1);
System.out.println(user);
}
}
Solution and Reason#
Since the primary key is not specified in the User entity class, the
selectById
method cannot find the primary key.
Therefore, the solution is to add @TableId(value = "user_id", type = IdType.AUTO)
in the User entity class.
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("user")
public class User {
// Add it here
@TableId(value = "user_id", type = IdType.AUTO)
@TableField("user_id")
private Long userId; // User ID
@TableField("user_name")
private String userName; // Username
@TableField("user_password")
private String userPassword; // User password
@TableField("user_authority")
private Integer userAuthority; // User authority
}