不使用实体类的情况下接收SQL查询结果、@Autowired注入为null解决

目录

一、场景

二、环境

三、使用

1、数据库表以及数据准备

2、项目导入必要依赖

3、添加连接数据库配置文件

4、编写测试方法

5、执行结果

四、将SQL单独提取出来

2.1 定义查询接口方法

2.2 测试

2.3 测试结果

五、问题记录: @Autowired注入失败/null的情况,

        1、通过上下文对象拿到Bean对象

        2、使用@PostConstruct注入

        3、实现ApplicationContextAware接口


一、场景

1、不使用实体类的情况下接收SQL查询结果

2、@Autowired注入为null解决

二、环境

springboot  2.7.0

maven 3.8

mysql 8.x

三、使用

        这边直接在测试方法中进行测试;

1、数据库表以及数据准备

-- boot_mybatis.t_user definition

CREATE TABLE `t_user` (
  `u_id` int NOT NULL AUTO_INCREMENT COMMENT '主键',
  `user_name` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '用户登录名',
  `email` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '邮箱',
  `pass_word` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '密码',
  `birth` date DEFAULT NULL COMMENT '生日',
  `gender` bigint NOT NULL DEFAULT '2' COMMENT '性别,0:男,1:女,2:保密',
  PRIMARY KEY (`u_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=89 DEFAULT CHARSET=utf8mb3 ROW_FORMAT=DYNAMIC;


INSERT INTO boot_mybatis.t_user (u_id, user_name, email, pass_word, birth, gender) VALUES(81, '李四', '[email protected]', '456', '2022-10-02', 0);
INSERT INTO boot_mybatis.t_user (u_id, user_name, email, pass_word, birth, gender) VALUES(82, '张三', '[email protected]', '123', '2022-10-02', 0);
INSERT INTO boot_mybatis.t_user (u_id, user_name, email, pass_word, birth, gender) VALUES(88, '李白', '[email protected]', '456', '2022-11-21', 1);

2、项目导入必要依赖

        
            org.springframework.boot
            spring-boot-starter-web
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.4.0
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            mysql
            mysql-connector-java
        

3、添加连接数据库配置文件

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3308/boot_mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&AllowPublicKeyRetrieval=True
    username: root
    password: root

4、编写测试方法

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public void test06() throws SQLException {
        DataSource dataSource = applicationContext.getBean(DataSource.class);
        Connection connection = dataSource.getConnection();
        Statement statement = connection.createStatement();
        String sql ="SELECT u_id , user_name, email, pass_word, birth, gender FROM boot_mybatis.t_user";
        ResultSet resultSet = statement.executeQuery(sql);

        // 组装保存查询结果的数据结构
        List> resultList = new ArrayList<>();
        List ids = new ArrayList<>();
        List userNames = new ArrayList<>();
        List emails = new ArrayList<>();
        Map resMap = new HashMap<>();
        while (resultSet.next()){
            String id = resultSet.getString(1);
            String userName = resultSet.getString(2);
            String email = resultSet.getString(3);
            ids.add(id);
            userNames.add(userName);
            emails.add(email);
        }

        resMap.put("id",ids);
        resMap.put("userName",userNames);
        resMap.put("email",emails);
        resultList.add(resMap);

       // 打印结果
       resultList.forEach(res->{
           System.out.println(res);
           // 某列的List
           Object resIds = res.get("id");
           System.err.println("resIds:"+resIds);
       });

        // 手动关闭
        statement.close();
        connection.close();
    } 
   

5、执行结果

四、将SQL单独提取出来

2.1 定义查询接口方法

@Mapper
public interface IUserMapper {

    List> selectUsers();
}

方法实现:

    

2.2 测试

    @Autowired
    private IUserMapper userMapper;

    @Test
    public void test02(){
        List> resultList = userMapper.selectUsers();
        resultList.forEach(res->{
            // 查看某列的结果
            String userName = res.get("userName").toString();
            System.out.println(userName);
        });
    }

2.3 测试结果

 不使用实体类的情况下接收SQL查询结果、@Autowired注入为null解决_第1张图片

五、问题记录: @Autowired注入失败/null的情况,

        检查必要注解是否均已添加、若依然注入失败、此处提供三种办法解决

不一定都适用、具体情况具体分析。以下方法我均已测试通过

        1、通过上下文对象拿到Bean对象

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public void test03(){
        IUserMapper userMapper = applicationContext.getBean(IUserMapper.class);
        userMapper.selectUsers();
    }

不使用实体类的情况下接收SQL查询结果、@Autowired注入为null解决_第2张图片

        2、使用@PostConstruct注入

@Component
public class IUserServiceTest {

    @Autowired
    private IUserMapper userMapper;
    static IUserServiceTest userService;

    @PostConstruct
    public void init(){
        userService  = this;
        userMapper = userService.userMapper ;
        userMapper.selectUsers();
    }
}

使用:

    @Autowired
    private IUserServiceTest userServiceTest;

    @Test
    public void test04(){
        userServiceTest.init();
    }

        3、实现ApplicationContextAware 接口

@Component
public class ApplicationContextHelper implements ApplicationContextAware {
    private static DefaultListableBeanFactory springFactory;
    private static ApplicationContext context;

    public ApplicationContextHelper() {
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }

    public static Object getBean( String beanName) {
      return context.getBean(beanName);
    }

    public static  T getBean(Class type) {
        return context.getBean(type);
    }
}

使用:通过类名调用静态方法即可

    @Test
    public void test05(){
        IUserMapper userMapper = ApplicationContextHelper.getBean(IUserMapper.class);
        userMapper.selectUsers();
    }

你可能感兴趣的:(springboot,常见问题纪录,数据库,java,mybatis,sql)