I have a spring-boot application with CRUD repository and a mysql database. When I use this repositories in a REST controller, I have no problems but I need to use one in a simple java class but it doesn't work.
I want to load all the residentStatEntities in a List to write in a CSV file but I can't load it.
Here are my code :
CRUD repository:
@Repository
public interface ResidentStatDBRepository extends CrudRepository<ResidentStatEntity, Long> {
List<ResidentStatEntity> findAll();
}
Java class :
public class ResetDB {
/**
* CRUD Repository
*/
@Autowired
private ResidentStatDBRepository residentStatDBRepository;
/**
* Delete DB and save his content in a CSV file
* @throws Exception
*/
public void save()throws Exception{
//open file
String csvFile = "residentStat.csv";
FileWriter writer = new FileWriter(csvFile, true);
//get list of all stat
List<ResidentStatEntity> residentStatEntities = residentStatDBRepository.findAll();
}
Here are the message print in the console :
java.lang.NullPointerException
at com.example.sems.ResetDB.save(ResetDB.java:36)
at com.example.sems.SemsApplication$1.run(SemsApplication.java:52)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
Here is where I use the ResetDB class
@SpringBootApplication
public class SemsApplication {
public static void main(String[] args) {
SpringApplication.run(SemsApplication.class, args);
int MINUTES = 1; // The delay in minutes
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() { // Function runs every MINUTES minutes.
try{
new ResetDB().save();
System.out.println("ok");
}catch (Exception e){
e.printStackTrace();
}
}
}, 0, 1000 * 60 * MINUTES);
// 1000 milliseconds in a second * 60 per minute * the MINUTES variable.
}
}
I call this function every minutes maybe the problem is because it's in the main method ?
Thanks in advance for you answer :)