Mybatis mysql 儲存Date型別的坑

2021-09-24 18:40:34 字數 2533 閱讀 9061

場景:把乙個時間字串轉成date,存進mysql。時間天數會比實際時間少1天,也可能是小時少了13-14小時

mysql的時區是cst(使用語句:show variables like '%time_zone%'; 查)

先放總結:

修改方法:1. 修改資料庫時區

2. 在jdbc.url裡加字尾&servertimezone=gmt%2b8

3. **裡設定時區,給******dateformat.settimezone(...)

例外:new date() 可以直接存為正確時間,其他的不行。比如我試過,把new date用sdf轉個2次,然後就錯誤了

貼一下測試的一下渣碼

// 1.new date()直接存資料庫則是正確的日期  結果:√ 190626,資料庫儲存正常

// date now = new date();

// 2,new date()用******dateformat轉化為字串再轉為date。結果: × 少1天 190625

// date now1 = new date();

// string tempstr = yymmddformatter.format(now1);

// string tempstrdate = tempstr.split(" ")[0];// 會加上00:00:00

// date date = yymmddformatter.parse(tempstrdate);

// 3.配置檔案加上&servertimezone=gmt%2b8,√ 正確

// 4. 設定中國標準時區 utc+8 結果:√

// ******dateformat sdf = new ******dateformat("yymmdd");

// 設定時區: 中國標準時 china standard time utc+08:00 使用gmt+8東8區,結果:?使用預設時區settimezone(timezone.getdefault);

// sdf.settimezone(timezone.gettimezone("utc+8"));

// system.out.println(sdf.gettimezone().tostring());

// date date = sdf.parse(liftmaxdt);

// system.out.println(sdf.gettimezone().tostring());

// system.out.println(date);

//// date targetdate = new date(date.gettime());

// system.out.println("------------------");

// system.out.println(targetdate);

// 5. 測試毫秒數 new date(ms);但是要先使用sdf轉入參 結果:× 問題就在於******dateformat會混亂時區

// ******dateformat sdf = new ******dateformat("yymmdd");

// date date = sdf.parse(liftmaxdt);

// date targetdate = new date(date.gettime());

// system.out.println("使用sdf轉換date,在new date(date.gettime())-----------");

// system.out.println(targetdate);

// 使用localdate.結果: × 還是少一天

datetimeformatter df = datetimeformatter.ofpattern("yymmdd");

localdate ldt = localdate.parse(liftmaxdt, df);

system.out.println("string型別的時間轉成localdatetime:"+ldt);

// localdate轉localdatetime

localdatetime lll = localdatetime.of(ldt, localtime.of(0,0,0));

zoneid zone = zoneid.systemdefault();

instant instant = lll.atzone(zone).toinstant();

date targetdate = date.from(instant);

// 將物件裡時間屬性設定為string,資料庫裡仍然用date,用資料庫的時間函式轉化

最後,還是採用的資料庫為timestamp型別,用mysql的時間函式進行轉換,保證時間為資料庫時間

mybatis mysql返回插入資料主鍵

工作中有這麼個需求 後邊資料依賴前邊插入資料的主鍵,所以需要插入返回主鍵 當然了,還有更好的方法,直接用mybatis配置關聯表,一次插入多個關聯表,但是這樣做的話,各個業務實體間的耦合度就回公升高,不利於擴充套件。最後,回歸到獲取返回主鍵處理,一般insert語句返回值是插入的條數,但是讓插入語句...

mybatis mysql 解決like傳值問題

在專案 基於ssm mysql 中需要使用到like 條件,於是搜尋了下相關的部落格,發現網上各種錯誤真是害死人,什麼concat寫成cancat,什麼標點符號錯誤,以及就一句話的部落格。故在此寫此部落格方便以後閱讀。like網上有3種方案,在此還是都貼出來吧,博主使用的第三種方案。省時高效。方法1...

MyBatis MySQL 返回插入的主鍵ID

需求 使用mybatis往mysql資料庫中插入一條記錄後,需要返回該條記錄的自增主鍵值。insert into basic organ buss parent id,buss name,buss alias,status,creater,create date,updater,update dat...