Reputation: 748
Trying to make a dao pattern for mybatis and spring. Want to use this sql queries anywhere i want, just using dependency injection. When i try to use this method (.getMaxId()) it gives me "Null pointer exception". Why field SqlSession is not autowiring(gives null)? Intellige idea shows this field as a canditate for autowiring.
I think there is 3 steps to achieve:
1) Autowire session
2) get mapper from session
3) execute queries from this mapper
I do this
@Autowired
private Student_mapper sm;
sm.getMaxId();
Service
@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 configuration file
@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 - interface with a queries
@Repository
public interface Student_mapper {
@Select("select max(id) from student")
@Result(property = "id", column = "ID")
Integer getMaxId();
}
Entity
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)
}
I don't understand what's wrong. There is any examples how to realise this? I would like to execute my queries anywhere i want without constantly initializing the session, datasource etc. Thanks in advance
Upvotes: 0
Views: 668