前後台Date類型資料處理

來源:互聯網
上載者:User
前台傳Date類型資料所導致的一系列問題

前台js傳過來的Date類型的資料格式預設為:
Fri Nov 18 2016 00:00:00 GMT+0800 (中國標準時間)
傳給後台使用Java.util.Date類型的屬性進行擷取的時候也儲存為這個格式,這就使在dao層拼接成sql語句的時候,處理不好之中的空格,導致語句執行時出現問題。
所以在後台對此進行處理
方法:
使用Java8新特性的LocalDate類
把Date類型資料轉換成LocalDate類型,再進行格式轉換

@Override    public int add(e_boms boms) {        Instant instant = boms.getApply_end_date().toInstant();        ZoneId zone = ZoneId.systemDefault();        LocalDateTime apply_end_date = LocalDateTime.ofInstant(instant,zone);//類型轉換        instant = boms.getApply_start_date().toInstant();        LocalDateTime apply_start_date = LocalDateTime.ofInstant(instant,zone);        DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");//設定轉換格式        String jpql = "insert into t_boms (foreign_key_id,code,material_id,apply_start_date,apply_end_date,mate) select count(*),"+boms.getCode()+","+boms.getMaterial_id()+",'"+apply_start_date.format(dateTimeFormatter)+"','"+apply_end_date.format(dateTimeFormatter)+"',0 from t_boms";//轉換格式後拼接        Query query = manager.createNativeQuery(jpql);        query.executeUpdate();        return boms.getId();    }

PS1:sql語句插入時間資料時,應該用單引號包圍起來。
PS2:jpql語句不支援insert操作,所以不能使用createQuery方法進行執行,必須改用createNativeAQuery方法執行原生的sql語句。此時要注意表名應該與資料庫中原本的相一致,而不能用實體名稱代替。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.