【发布时间】:2020-02-28 19:18:21
【问题描述】:
我尝试制作控制台 myBatis 应用程序并摆脱多次使用相同的代码来初始化会话、执行提交和事务。这段代码在 Annotations_Example 类的“sm”字段中为我提供了“空指针值”。我做错了什么?在类初始化中,一切正常。但现在,它有了 NPE。
数据源类
public class DataSourceStudent_Mapper {
@Bean
public Student_mapper 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.getMapper(Student_mapper.class);
}
}
主类
public class Annotations_Example {
@Autowired
public Student_mapper sm;
public static void main(String args[]) throws IOException {
Student student = new Student();
student.setName("zara");
student.setBranch("EEE");
student.setEmail("zara@gmail.com");
student.setPercentage(90);
student.setPhone(123412341);
sm.insert(student);
sm.getMaxId();
session.commit();
session.close();
}
}
【问题讨论】:
标签: null annotations mybatis autowired inject