Mybatis dao模式未自动装配字段

问题描述 投票:0回答:1

[试图为Mybatis和春天制作dao模式。想要在我想要的任何地方使用此sql查询,只需使用依赖项注入即可。当我尝试使用此方法(.getMaxId())时,它给我“空指针异常”。为什么字段SqlSession不自动装配(给null)?聪明的想法将此字段显示为自动接线。

我认为有3个步骤可以实现:

1自动连线会话

2)从会话中获取映射器

3)从此映射器执行查询

我这样做

@Autowired
 private Student_mapper sm;

sm.getMaxId();

服务

@Service
@Transactional
public class Student_mapperImpl {

    @Autowired
    private SqlSession session;

    @Autowired
    Student_mapper mapper = session.getMapper(Student_mapper.class);


    public Integer getMaxId() {

        Integer value = mapper.getMaxId();

        return value;
    }
}

Bean配置文件

 @org.springframework.context.annotation.Configuration
    @EnableTransactionManagement
    @ComponentScan
    public class DataSourceStudent_Mapper {

        @Bean
        public SqlSession getDataSource() {

         String user = "postgres";
         String password = "postgres";
         String databasenameURL = "jdbc:postgresql://localhost:5432/postgres";
         String dbDriver = "org.postgresql.Driver";
         DataSource dataSource = new org.apache.ibatis.datasource.pooled.PooledDataSource(
                 dbDriver, databasenameURL, user, password);
         TransactionFactory transactionFactory = new JdbcTransactionFactory();
         Environment environment = new Environment("development",
                 transactionFactory, dataSource);
         Configuration configuration = new Configuration(environment);
         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                 .build(configuration);
         SqlSession session = sqlSessionFactory.openSession();
         session.getConfiguration().addMapper(Student_mapper.class);

        return session;
        }
    }

Student_mapper-查询界面

@Repository
public interface Student_mapper {
    @Select("select max(id) from student")
    @Result(property = "id", column = "ID")
    Integer getMaxId();
}

实体

public class Student {
    private int id;
    private String name;
    private String branch;
    private int percentage;
    private int phone;
    private String email;
    //(setters,getters, allArgs constructor are ommited)
}

我不明白怎么了。有任何示例如何实现这一目标?我想在我想要的任何地方执行查询,而无需不断初始化会话,数据源等。预先感谢

spring dependency-injection mybatis autowired dao
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.