Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如果mysql的字段类型是enum, 如何映射 是否已经有参考的案例 #6135

Closed
cnscud opened this issue May 6, 2024 · 2 comments
Closed

Comments

@cnscud
Copy link

cnscud commented May 6, 2024

例如mysql的字段为:

type enum('project','task','execution') NOT NULL DEFAULT 'project',
deleted enum('0','1') NOT NULL DEFAULT '0',

多谢

@miemieYaho
Copy link
Member

没有

@cnscud
Copy link
Author

cnscud commented May 6, 2024

研究了一下, 使用一个定制的typeHandler可以实现:

/**

  • Type Handler for like "Status" Enum String field.

  • @author Felix Zhang 2024-05-06 10:30

  • @Version 1.0.0
    */
    @MappedJdbcTypes({JdbcType.OTHER})
    @MappedTypes({String.class})
    @slf4j
    public class StringEnumTypeHandler extends BaseTypeHandler {

    @OverRide
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
    log.info("String: " + parameter);
    ps.setString(i, parameter);
    }

    @OverRide
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
    log.info("value: " + rs.getString(columnName));
    return (T) rs.getString(columnName);
    }

    @OverRide
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    return (T) rs.getString(columnIndex);
    }

    @OverRide
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    return (T) cs.getString(columnIndex);
    }

}

然后在mybatis配置里配置 type-handlers-package 为你的包名

然后Java里使用String类型, Jdbc类型就用Other就可以.

Java里也可以用 Integer, 不过就要另外写一个typeHandler了.

@cnscud cnscud closed this as completed May 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants