javaee创建员工表(emp_id,emp_name,emp_age,emp_sex,emp_email)和部门表(dept_id,dept_name),完成查询功能:根据id查询员工以及其所在信息
时间: 2024-09-23 20:10:34 浏览: 47
JavaEE源代码 jdbc2_0-stdext
在Java EE中,你可以使用JPA (Java Persistence API) 或者直接使用SQL语句来创建数据库表并实现查询功能。首先,我们需要定义实体类(Entity),例如Employee和Department。
```java
// Employee.java
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long empId;
private String empName;
private Integer empAge;
private String empSex;
private String empEmail;
// getters and setters
}
// Department.java
@Entity
@Table(name = "departments")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long deptId;
private String deptName;
// getters and setters
}
```
然后,你需要配置数据源、EntityManagerFactory等,并通过Repository接口来执行CRUD操作,包括查询:
```java
// EmployeeRepository.java (假设使用Spring Data JPA)
import org.springframework.data.jpa.repository.JpaRepository;
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
Employee findById(Long id);
}
```
现在,你可以创建EmployeeRepository的实例,根据ID查询员工及其所在部门的信息:
```java
@Service
public class UserService {
private final EmployeeRepository employeeRepository;
public UserService(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
public Employee getEmployeeAndDeptInfo(Long id) {
Employee employee = employeeRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Employee not found", Employee.class, id));
// 如果需要获取部门信息,可以这样做,假设有一个DepartmentRepository
Department department = departmentRepository.findById(employee.getDeptId()).orElse(null); // 这里假设已有一个DepartmentRepository
employee.setDepartment(department);
return employee;
}
}
// 使用时
Employee employee = userService.getEmployeeAndDeptInfo(1L);
System.out.println(employee.getEmpName() + " is in " + employee.getDepartment().getDeptName());
```
阅读全文