简体   繁体   English

使用springboot向数据库中的所有到期项目发送警报电子邮件时出错

[英]Getting error while sending alert emails to all due items in DB using springboot

I am developing an api using Springboot, which will check the DB and find all the email ids in an action table and send alert emails.I could start the springboot applciation with no error.我正在使用 Springboot 开发一个 api,它将检查数据库并在操作表中查找所有电子邮件 ID 并发送警报电子邮件。我可以启动 springboot 应用程序而没有错误。 But when i send the http://localhost:8082/send-due-emails request in postman, I get the below error in the application但是当我在邮递员中发送 http://localhost:8082/send-due-emails 请求时,我在应用程序中收到以下错误

Cannot invoke "com.emailschedulerfinal.repository.EmailRepository.findDueEmails()" because "this.emailrepo" is null无法调用“com.emailschedulerfinal.repository.EmailRepository.findDueEmails()”,因为“this.emailrepo”为空

The query I use is returning the results in DB.我使用的查询是在 DB 中返回结果。 It has got two email ids in the results.结果中有两个电子邮件 ID。 Can you please help me with this issue?你能帮我解决这个问题吗? Anything wrong in the way I gave the query in the repository?我在存储库中提供查询的方式有什么问题吗? Or any issue with the return statements here?或者这里的返回语句有什么问题?

This is my Controller这是我的控制器

@RestController
public class EmailController {

    SchedulerService schedulerservice = new SchedulerService(null);
    @RequestMapping("send-due-emails")
    public String send() {
        try {
            schedulerservice.sendEmailIds();
        } catch (MailException mailException) {
            System.out.println(mailException);
        }
        return "Congratulations! Your mail has been sent to the user.";
    }

}

This is my model这是我的模型

@Entity
@Table(name = "actionitems")
public class actionitems {
    
    @Id
    @GeneratedValue
    private int id;
    private String action;
    private String email;
    private Date duedate;
#getters and setters omitted here
}

This is my repository这是我的存储库

    public interface EmailRepository extends JpaRepository<actionitems, Long> {
       @Query("select email from actionitems where duedate< CURRENT_TIMESTAMP")     
       public List<String[]> findDueEmails();
                    
}

This is my service这是我的服务

public class SchedulerService {
    private JavaMailSender javaMailSender;
    
    @Autowired
    EmailRepository emailrepo;


    public SchedulerService(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    public List<String[]> findDueEmailsFromDB() {
        
        return emailrepo.findDueEmails();
    }
    
    public void sendEmailIds() {
        
        List<String[]> To = findDueEmailsFromDB();
        String k[] = To.toArray(new String[To.size()]);
        
        System.out.println("The list obtained is " + k);
         
        // Iterating over above string array
        for (String str : k) {
 
            // Printing the elements in above array
            System.out.println(str);
        }
       

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setTo(k);
        mailMessage.setSubject("sample subject");
        mailMessage.setText("Sample text");
        mailMessage.setFrom("test@gmail.com");
        javaMailSender.send(mailMessage);
        }
}

I got a workaround for this.我有一个解决方法。 Instead of using query annotations, if I write a utility class which connect to db and run the query and return the results, it is sending emails to all those email ids .But still I would like to know how to make the same work using @Query annotation in springboot.如果我不使用查询注释,而是编写一个连接到数据库并运行查询并返回结果的实用程序类,它将向所有这些电子邮件 ID 发送电子邮件。但我仍然想知道如何使用 @ 进行相同的工作springboot中查询注解。

 public static Connection connect() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }
    public static ArrayList<String> getdueEmails() throws SQLException, ClassNotFoundException{
        ArrayList<String> a = new ArrayList<String>();

        Connection con = connect();
        PreparedStatement ps = con.prepareStatement("select email from actionitems_final where duedate< CURRENT_TIMESTAMP");
        ResultSet rs = ps.executeQuery();
       

        while(rs.next())
        {
            a.add(rs.getString(1));
        }

        return a;
    }

This is my service这是我的服务

public void sendEmail() throws MailException, ClassNotFoundException, SQLException {

    SQLhelper sqlhelper = new SQLhelper();
    /*
     * This JavaMailSender Interface is used to send Mail in Spring Boot. This
     * JavaMailSender extends the MailSender Interface which contains send()
     * function. SimpleMailMessage Object is required because send() function uses
     * object of SimpleMailMessage as a Parameter
     */
    List<String> To = sqlhelper.getdueEmails();
    String k[] = To.toArray(new String[To.size()]);

    SimpleMailMessage mail = new SimpleMailMessage();

    mail.setTo(k);
    mail.setSubject("Email to all persons having due date");
    mail.setText("This is sent to all email ids corresponding to actions which are due today...");

    /*
     * This send() contains an Object of SimpleMailMessage as an Parameter
     */
    javaMailSender.send(mail);
}

Finally I found the issue with my query annotation.最后我发现了我的查询注释的问题。 Earlier both the model class name and my DB table name were the same.早些时候模型类名和我的数据库表名是相同的。 We have to use the model class name inside the query annoatation and not the db table name.我们必须在查询注释中使用模型类名,而不是数据库表名。

This is my repository这是我的存储库

public interface EmailRepository extends JpaRepository<ActionItems, String> {
    @Query("select email from ActionItems where duedate< CURRENT_TIMESTAMP")
    List<String> finddueemailsfromdb();

}

This is my entity这是我的实体

@Entity
@Table(name = "actionitemsFinal")
public class ActionItems {
    
    @Id
    @GeneratedValue
    private int id;
    private String action;
    private String email;
    private Date duedate;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getAction() {
        return action;
    }
    public void setAction(String action) {
        this.action = action;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Date getDuedate() {
        return duedate;
    }
    public void setDuedate(Date duedate) {
        this.duedate = duedate;
    }

}

This is my Service这是我的服务

List<String> To = emailrepo.finddueemailsfromdb();
String k[] = To.toArray(new String[To.size()]);
SimpleMailMessage mail = new SimpleMailMessage();
/* mail.setTo(actions.getEmailAddress()); */
mail.setTo(k);
  ......rest of the code omitted

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM