I have searched various GPT and CSDN articles, but I haven't found the correct solution. It is commonly said that it is an issue with 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
in the User entity class to specify the primary key @TableId(value = "user_id", type = IdType.AUTO)
@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
}