现有员工表employee,字段id,name,age,position。要求:在数据库建立该表,并插入初始数据。 使用Mybatis完成一下几个功能: (1)根据id查询员工信息 (2)新增员工信息 (3)根据id修改员工信息 (4)根据id删除员工信息
时间: 2024-09-25 19:06:59 浏览: 35
在MyBatis中,首先需要创建对应的XML映射文件,以及Java配置文件来进行持久层的操作。以下是四个功能的具体步骤:
1. 创建EmployeeMapper.xml映射文件:
```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.example.mapper.EmployeeMapper">
<!-- 根据id查询员工 -->
<select id="getEmployeeById" parameterType="int" resultType="com.example.entity.Employee">
SELECT * FROM employee WHERE id = #{id}
</select>
<!-- 新增员工 -->
<insert id="addEmployee" parameterType="com.example.entity.Employee">
INSERT INTO employee (id, name, age, position)
VALUES (#{id}, #{name}, #{age}, #{position})
</insert>
<!-- 修改员工信息 -->
<update id="updateEmployeeById" parameterType="com.example.entity.Employee">
UPDATE employee SET name = #{name}, age = #{age}, position = #{position} WHERE id = #{id}
</update>
<!-- 删除员工信息 -->
<delete id="deleteEmployeeById" parameterType="int">
DELETE FROM employee WHERE id = #{id}
</delete>
</mapper>
```
2. 在Java配置中注册这个Mapper并提供DAO接口:
```java
package com.example.mapper;
import com.example.entity.Employee;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Delete;
public interface EmployeeMapper {
@Select("SELECT * FROM employee WHERE id = #{id}")
Employee getEmployeeById(int id);
@Insert("INSERT INTO employee (id, name, age, position) VALUES (#{id}, #{name}, #{age}, #{position})")
void addEmployee(Employee employee);
@Update("UPDATE employee SET name = #{name}, age = #{age}, position = #{position} WHERE id = #{id}")
void updateEmployeeById(Employee employee);
@Delete("DELETE FROM employee WHERE id = #{id}")
void deleteEmployeeById(int id);
}
```
阅读全文