Spring JDBC插入数据库将不起作用

时间:2018-07-24 20:42:08

标签: spring spring-boot jdbc spring-jdbc jdbctemplate

由于某种原因,我的jdbctemplate没有在application.properties文件中获取信息。我只有在建立自己的连接时才可以在数据库中插入我的用户名和密码。 Spring Boot为什么不接呢?请帮忙!

我仍在从多个RFID读取器读取标签的同时调用addTaglocation模式。这会引起问题吗?如果是这样,我该如何解决。预先感谢。

我开始从控制器的多个rfid读取器读取标签。

我在其中调用create方法(addTaglocation方法)的完整类:

public class TagInventory extends AlienClass1Reader implements 
    MessageListener, TagTableListener{

    private final int MAX_THREAD = 50;
    private Thread[] m_run_process = new Thread[MAX_THREAD];
   private AlienReader[] m_inventory = new AlienReader[MAX_THREAD];
   public boolean stopInventory = false;
     ReaderProfileService rps;
     VehicleService vs;
    private boolean ThreadStop = true;
    private int lastThreadId = -1;
      private MessageListenerService service;
    private TagTable tagTable = new TagTable();
     private TagTableListener tagTableListener;

     private static final Logger log =LogManager.getLogger(TagInventory.class);


     @Autowired 
     TaglocationDAOJdbc taglocationDAOJdbc;


    public TagInventory() throws AlienReaderException, IOException{
        Start();
    }

    public void stopTag() throws AlienReaderException{
        Stop();
    }

    private void Stop() throws AlienReaderException{
         ThreadStop = true;
         for (lastThreadId=0; lastThreadId < Reader.ipAddress.length; 
    lastThreadId++){
             if(m_inventory[lastThreadId] != null){
                 m_inventory[lastThreadId].stopInventory = true;
                 service.stopService();
                 try{
                     Thread.sleep(200);
                 }catch(Exception e){
                     e.getMessage();
                 }

                 //m_inventory[lastThreadId].close();

                 m_inventory[lastThreadId].open();
                 m_inventory[lastThreadId].autoModeReset();
                 m_inventory[lastThreadId].setAutoMode(AlienClass1Reader.OFF);
                 m_inventory[lastThreadId].setNotifyMode(AlienClass1Reader.OFF);
                 m_inventory[lastThreadId].close();


             }
         }

    }

    private void Start() throws AlienReaderException, IOException{
        ThreadStop = false;

         service= new MessageListenerService(3900);
         service.setMessageListener(this);
         service.startService();

          for (lastThreadId = 0; lastThreadId < Reader.ipAddress.length; lastThreadId++)
          {
              m_inventory[lastThreadId] = new AlienReader(Reader.ipAddress[lastThreadId], Reader.port, Reader.username[lastThreadId], Reader.password[lastThreadId]);
              log.info("taginventory reader: "+ Reader.ipAddress[lastThreadId]+"Thread: "+lastThreadId);
              m_run_process[lastThreadId] = new Thread(new StartInventoryThread(Reader.ipAddress[lastThreadId], Reader.port, Reader.username[lastThreadId], Reader.password[lastThreadId], m_inventory[lastThreadId]));
              m_run_process[lastThreadId].start();
          }
          --lastThreadId;

          try
          {
              Thread.sleep(1000);
          }
          catch (Exception ex)
          {
              ex.getMessage();
          }


    }

    class StartInventoryThread implements Runnable{

        private String ip;
        private int port;
        private String user;
        private String pwd;
        private AlienReader ar;


        StartInventoryThread(String ip, int port, String user, String pwd, AlienReader ar){
            this.ip=ip;
            this.port=port;
            this.user=user;
            this.pwd=pwd;
            this.ar=ar;
        }


        @Override
        public void run() {
            try {
                while(!stopInventory){
                    startRead(ip,port,user,pwd);
                }
            } catch (AlienReaderException | InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }

    @Override
    public void tagAdded(Tag tag) {
        log.info("NEW TAG: " + tag.getTagID()+ " LAST SEEN DATE: "+ tag.getRenewTime());

    }

    @Override
    public void tagRemoved(Tag tag) {
        // TODO Auto-generated method stub          
    }

    @Override
    public void tagRenewed(Tag tag) {
        // TODO Auto-generated method stub          
    }

    @Override
    public synchronized void messageReceived(Message msg) {
         if(msg instanceof ErrorMessage){
            //   log.info("Notify error from " + msg.getReaderIPAddress());

         }else if (msg.getTagCount() == 0){

                    log.info("No tags!");
         }else{
            //log.info("Message received from: "+msg.getReaderIPAddress());
            Tag[] tagL=msg.getTagList();
            //String[] tagLString=new String[tagL.length];
            for (int i=0;i<msg.getTagCount(); i++){
                Tag tag = msg.getTag(i);
                //System.out.println("Tag ID: "+tag.getTagID()+ " Last Seen: "+tag.getRenewTime());
                this.tagTable.addTag(tag);
                // log.info("Tag ID: "+tag.getTagID()+ " Last Seen: "+tag.getRenewTime()+ " Receive Antenna: "+tag.getReceiveAntenna());

                //System.out.println("Tag: "+tag+ " Last Seen: "+tag.getRenewTime());
            }

          }
         //check readerprofile
          try {
            updateLocation(Reader.ipAddress[this.lastThreadId]);
             this.tagTable.removeOldTags();
        } catch (NoReaderInfoException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoVehicleException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void addTaglocation(Taglocation tl){
        Taglocation newtagloca= new Taglocation(tl.getReadername(),tl.getRfidtag(),tl.getZone(), tl.getTaggingsource(), tl.getVineight(), tl.getZonedate());


    taglocationDAOJdbc.addtaglocation(newtagloca);
        log.info("ADDED TAGG INFO!");           
    }

    public void updateLocation(String read) throws NoReaderInfoException, NoVehicleException{
        //update location of vehicle when tag read by readers
        log.info("IN UPDATE LOCATION with reader: "+read);
         Tag[] temp;

         temp=this.tagTable.getTagList();

         for (int i = 0; i < temp.length; i++) {
             log.info("get taglist");
                Tag tag = temp[i];
                String rfid=tag.getTagID();
                Timestamp newDate=new Timestamp(Calendar.getInstance().getTime().getTime());
                Taglocation tl=new Taglocation(read, rfid, read, "", "vineight", newDate);
                addTaglocation(tl);

         }


}


    public void startRead(String ip, int port, String user, String password) throws AlienReaderException, InterruptedException, UnknownHostException{
        String myIP=InetAddress.getLocalHost().getHostAddress();
        System.out.println("ip"+ ip);
        AlienReader ar= new AlienReader(ip, port, user, password);
        ar.open();
         log.info("Reader" + ar.getIPAddress());

        ar.setNotifyAddress(myIP, 3900);
        ar.setNotifyFormat(AlienClass1Reader.TEXT_FORMAT);
        ar.setNotifyTrigger("TrueFalse");
        ar.setNotifyMode(AlienClass1Reader.ON);

        ar.autoModeReset();
        ar.setAutoStopTimer(5000); // Read for 5 seconds
        ar.setAutoMode(AlienClass1Reader.ON);
        tagTable.setTagTableListener(tagTableListener);
        tagTable.setPersistTime(5000);

        //tagTable.setPersistTime(1800000);
        ar.close();

        long runTime = 10000; // milliseconds
         long startTime = System.currentTimeMillis();
         do {
         Thread.sleep(1000);
         } while(service.isRunning()
         && (System.currentTimeMillis()-startTime) < runTime);

         // Reconnect to the reader and turn off AutoMode and TagStreamMode.
         log.info("\nResetting Reader");
        ar.open();
        ar.autoModeReset();
        ar.setNotifyMode(AlienClass1Reader.OFF);
        ar.close();

    }




}


(UPDATED)

Application.properties文件:

spring.datasource.url=jdbc:mysql://localhost:3306/DB
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

(已更新) taglocationJDBCTemplate文件

@Repository
public class TaglocationJDBCTemplate implements TaglocationDAO {

    @Autowired
    JdbcTemplate jdbcTemplate;


    public void create(Taglocation tl){
    KeyHolder keyHolder = new GeneratedKeyHolder();

    jdbcTemplate.update(new PreparedStatementCreator(){
            public PreparedStatement createPreparedStatement(final Connection connection) throws SQLException {
             PreparedStatement ps = connection.prepareStatement("INSERT INTO TAGLOCATION (READERNAME, RFIDTAG, TAGGINGSOURCE, ZONE, VINEIGHT, ZONEDATE) VALUES (?,?,?,?,?,?)",
                     Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, tl.getReadername());
            ps.setString(2,tl.getRfidtag());
            ps.setString(3, tl.getTaggingsource());
            ps.setString(4, tl.getZone());
            ps.setString(5, tl.getVineight());
            ps.setTimestamp(6, new Timestamp(System.currentTimeMillis())); 
             return ps;
          }
    }, keyHolder);
    return (Integer) keyHolder.getKey();
}

控制文件:

@RestController
public class TagInventoryController {

  @Autowired
  TagService tagService;


  @RequestMapping("/runTasks")
  public String tagRead(){
    tagService.startTagRead();
    return "Readers are activated.";
  }
}

0 个答案:

没有答案