Fundamentals 7 min read

Understanding Java Enums: Usage, Switch Cases, Singleton Implementation, and Database Integration

This article explores Java enums in depth, covering their basic definition, typical usage patterns such as iteration and switch statements, implementing singletons, integrating with databases via MyBatis type handlers, and addressing common misconceptions about memory consumption, illustrating each concept with clear code examples.

Java Captain
Java Captain
Java Captain
Understanding Java Enums: Usage, Switch Cases, Singleton Implementation, and Database Integration

Java enums are a powerful language feature that can make code more elegant and type‑safe. The article begins by introducing a simple enum definition and shows how to create and iterate over its values.

public enum Chenmo {
    WANGER, WANGSAN, WANGSI
}

Iterating over the enum values is straightforward:

for (Chenmo e : Chenmo.values()) {
    System.out.println(e);
}

Using an enum as the condition in a switch statement improves readability and prevents accidental string mismatches:

Chenmo key = Chenmo.WANGER;
switch (key) {
    case WANGSI:
        System.out.println("今天我送出一个CSDN大鼠标垫");
        break;
    case WANGSAN:
        System.out.println("今天我被坑一个CSDN学院年卡");
        break;
    default:
        System.out.println("今天我一边高兴,一边失落");
        break;
}

The article then discusses the recommended way to implement a singleton using an enum, as advocated by Effective Java . The enum‑based singleton is concise and automatically provides serialization safety and thread safety.

public enum SingleTon {
    INSTANCE;
    public void method() {
        System.out.println("我很快乐!");
    }
}

Next, the article shows how enums can be mapped to database fields with MyBatis. A more complex enum CheckType includes an integer key and a descriptive text, plus a static parse method for conversion.

public enum CheckType {
    NO_PASS(0, "未通过"),
    PASS(1, "通过");
    private int key;
    private String text;
    private CheckType(int key, String text) {
        this.key = key;
        this.text = text;
    }
    public int getKey() { return key; }
    public String getText() { return text; }
    private static final Map<Integer, CheckType> map = new HashMap<>();
    static { for (CheckType d : CheckType.values()) { map.put(d.key, d); } }
    public static CheckType parse(Integer index) { return map.getOrDefault(index, null); }
}

A MyBatis typeHandler uses this parse method to convert the integer column check_type into the appropriate enum instance.

public class CheckTypeHandler extends BaseTypeHandler<CheckType> {
    @Override
    public CheckType getNullableResult(ResultSet rs, String column) throws SQLException {
        return CheckType.parse(rs.getInt(column));
    }
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, CheckType val, JdbcType jt) throws SQLException {
        ps.setInt(i, val.getKey());
    }
    // other overrides omitted for brevity
}

Finally, the article addresses a common question: do enums consume more memory than static constants? The author argues that the difference is negligible and that the benefits of type safety and built‑in functionality outweigh any minor overhead.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavadatabaseenumMyBatisSingleton
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.