SoFunction
Updated on 2025-03-03

How to deposit List into a database by MyBatisPlus3

MyBatisPlus3 deposits List into the database

Official website:/guides/type-handler/

Example

  • Java data types:
List<String>
  • JSON string stored in the database:
["user", "edu-admin"]

@TableName(autoResultMap = true)
public class User implements Serializable {
    @TableField(typeHandler = )
    private List<String> roles;
}

<resultMap  type="">
  <result property="roles" column="roles" typeHandler="" jdbcType="VARCHAR"/>
</resultMap>

JSON parser

package ;

import ;
import .*;

import ;
import ;
import ;
import ;
import ;
import ;

@MappedTypes()
@MappedJdbcTypes()
public class ListToVarcharTypeHandler implements TypeHandler&lt;List&lt;String&gt;&gt; {

    public void setParameter(PreparedStatement preparedStatement, int i, List&lt;String&gt; strings, JdbcType jdbcType) throws SQLException {
        // traverse the parameters of List type, assemble it into String type, and insert it into the database using Statement object        StringBuffer sb = new StringBuffer();
        for (int j = 0; j &lt; (); j++) {
            if (j == () - 1) {
                ((j));
            } else {
                ((j)).append(",");
            }
        }
        (i, ());
    }

    @Override
    public List&lt;String&gt; getResult(ResultSet resultSet, String s) throws SQLException {
        // Get the result of String type, use "," to split it into List and return it        String resultString = (s);
        if ((resultString)) {
            return ((","));
        }
        return null;
    }

    @Override
    public List&lt;String&gt; getResult(ResultSet resultSet, int i) throws SQLException {
        // Get the result of String type, use "," to split it into List and return it        String resultString = (i);
        if ((resultString)) {
            return ((","));
        }
        return null;
    }

    @Override
    public List&lt;String&gt; getResult(CallableStatement callableStatement, int i) throws SQLException {
        // Get the result of String type, use "," to split it into List and return it        String resultString = (i);
        if ((resultString)) {
            return ((","));
        }
        return null;
    }
}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.