mybatis 自定義類型轉換器 (后台日期類型插入數據庫)


后台日期類型插入數據庫 有以下幾種發法:

1 調用數據庫 日期字符串轉日期函數 str_to_date("日期","yyyy-MM-dd HH:mm:ss")

2. INSERT INTO person (NAME,sex,DATE) VALUES ('${name}','${sex}',#{date ,javaType=java.util.Date,jdbcType=TIMESTAMP}

3 自定義類型轉換器:(2,3方法里插值符號必須為 # 號)

泛型類型為Java-->jdbc    set方法把Java-->jdbc   get方法  jdbc -->java 數據庫到Java 可以bean 日期屬性加 @dateformat()注解

public
class Myconvert extends BaseTypeHandler<Date> { public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException { String d=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date); preparedStatement.setString(i,d ); } public Date getNullableResult(ResultSet resultSet, String s) throws SQLException { return resultSet.getDate(s); } public Date getNullableResult(ResultSet resultSet, int i) throws SQLException { String d=resultSet.getString(i); try { return (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).parse(d); } catch (ParseException e) { e.printStackTrace(); } return null; } public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException { return null; } }

自定義完 配置文件里注冊

<typeHandlers>
  <typeHandler handler="com.mybatis.convert.Myconvert" javaType="java.util.Date" jdbcType="TIMESTAMP"/>

</typeHandlers>

注冊完使用 

 INSERT INTO person (NAME,sex,DATE) VALUES ('${name}','${sex}',#{date,typeHandler=com.mybatis.convert.Myconvert})

  

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM