You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从数据库获取数据及Emp.java类代码相关技术咨询

从数据库获取数据 & Emp.java 实操指南

Hey there! Let's walk through how to fetch data from a database and map it to your Emp class. First, let's fix up that incomplete setDesignation method in your code, then cover the most common implementation approaches you can use.

一、先补全你的Emp.java类

Your code snippet was missing the full setDesignation method—here's the complete, standard POJO (Plain Old Java Object) that works perfectly for database mapping:

package com.javatpoint;
public class Emp {
    private int id;
    private String name;
    private float salary;
    private String designation;

    // Getter methods
    public int getId() { return id; }
    public String getName() { return name; }
    public float getSalary() { return salary; }
    public String getDesignation() { return designation; }

    // Setter methods
    public void setId(int id) { this.id = id; }
    public void setName(String name) { this.name = name; }
    public void setSalary(float salary) { this.salary = salary; }
    public void setDesignation(String designation) { this.designation = designation; }
}

This class matches a typical emp database table (assuming columns are id, name, salary, designation). It uses standard getter/setter pairs so frameworks or manual code can easily populate its fields.

二、从数据库获取数据并映射到Emp的常见实现方式

1. 原生JDBC (基础手动实现)

If you want to stick to vanilla Java without frameworks, this is the foundational approach. You handle connections, SQL execution, and result mapping manually:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class JdbcEmpDao {
    // Replace these with your actual database credentials
    private static final String DB_URL = "jdbc:mysql://localhost:3306/your_database_name";
    private static final String DB_USER = "your_username";
    private static final String DB_PASS = "your_password";

    public List<Emp> getAllEmployees() {
        List<Emp> employees = new ArrayList<>();
        String sql = "SELECT id, name, salary, designation FROM emp";

        // Use try-with-resources to auto-close connections/statements (avoids leaks!)
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                Emp emp = new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getFloat("salary"));
                emp.setDesignation(rs.getString("designation"));
                employees.add(emp);
            }
        } catch (Exception e) {
            // In production, use proper logging instead of printStackTrace()
            e.printStackTrace();
        }
        return employees;
    }
}

Pro tip: Always use try-with-resources for JDBC resources—they auto-close when the block finishes, so you don't have to remember to call .close() manually.

2. Spring JdbcTemplate (简化JDBC代码)

If you're using the Spring Framework, JdbcTemplate takes care of all the repetitive JDBC boilerplate (connection management, exception handling, etc.). Here's how to use it:
First, make sure you have Spring's JDBC dependencies set up. Then implement your DAO:

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.util.List;

public class SpringEmpDao {
    private JdbcTemplate jdbcTemplate;

    // Inject your DataSource (configured via Spring XML or annotations)
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public List<Emp> getAllEmployees() {
        String sql = "SELECT id, name, salary, designation FROM emp";
        // BeanPropertyRowMapper auto-maps ResultSet columns to Emp's fields (matches getter/setter names)
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Emp.class));
    }

    // Fetch a single employee by ID
    public Emp getEmployeeById(int id) {
        String sql = "SELECT id, name, salary, designation FROM emp WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(Emp.class));
    }
}

BeanPropertyRowMapper is a huge time-saver—it automatically matches column names to your Emp class's property names (using the setter methods), so you don't have to manually assign each field like in raw JDBC.

3. MyBatis (ORM Framework)

MyBatis is a flexible ORM tool that lets you map SQL to Java objects via annotations or XML. It's great if you want more control over SQL than JPA provides.

Option 1: Annotation-Based Mapping

Define a Mapper interface with SQL annotations:

import org.apache.ibatis.annotations.Select;
import java.util.List;

public interface EmpMapper {
    @Select("SELECT id, name, salary, designation FROM emp")
    List<Emp> getAllEmployees();

    @Select("SELECT id, name, salary, designation FROM emp WHERE id = #{id}")
    Emp getEmployeeById(int id);
}

Then use MyBatis's SqlSession to call the mapper:

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class MyBatisEmpDao {
    private final SqlSessionFactory sqlSessionFactory;

    public MyBatisEmpDao(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    public List<Emp> getAllEmployees() {
        // Auto-close the session with try-with-resources
        try (SqlSession session = sqlSessionFactory.openSession()) {
            EmpMapper mapper = session.getMapper(EmpMapper.class);
            return mapper.getAllEmployees();
        }
    }
}

Option 2: XML-Based Mapping

If you prefer to keep SQL in separate XML files (good for complex queries), create EmpMapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.javatpoint.EmpMapper">
    <select id="getAllEmployees" resultType="com.javatpoint.Emp">
        SELECT id, name, salary, designation FROM emp
    </select>
    <select id="getEmployeeById" parameterType="int" resultType="com.javatpoint.Emp">
        SELECT id, name, salary, designation FROM emp WHERE id = #{id}
    </select>
</mapper>

Then call the mapper the same way as the annotation version—MyBatis will handle the XML mapping automatically.

三、Key Things to Keep in Mind

  • Column-Property Matching: Make sure your database column names match your Emp class's property names (or use SQL aliases like SELECT emp_id AS id ... if they don't).
  • Null Handling: If your database allows salary to be null, change the salary field in Emp to Float (the wrapper class) instead of float—raw primitives can't hold null values, and ResultSet.getFloat() will return 0.0 for nulls, which is misleading.
  • Security: Never hardcode database credentials in your code—use environment variables, configuration files, or a secrets manager instead.
  • Logging: In production, replace printStackTrace() with a proper logging framework like SLF4J/Logback to track errors properly.

内容的提问来源于stack exchange,提问作者Jalla Srinivasarao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:41:33