1.Spring-mybatis-新增实现-主键回显

This commit is contained in:
2025-09-25 16:26:03 +08:00
parent 784f2e5603
commit ff1aa03490
3 changed files with 31 additions and 1 deletions

View File

@@ -1,7 +1,10 @@
package com.inmind.mapper; package com.inmind.mapper;
import com.inmind.pojo.Emp;
import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
@Mapper @Mapper
public interface EmpMapper { public interface EmpMapper {
@@ -16,4 +19,11 @@ public interface EmpMapper {
// public void delete(Integer id); // public void delete(Integer id);
@Delete("delete from emp where id = #{id};") @Delete("delete from emp where id = #{id};")
public int delete(Integer id); public int delete(Integer id);
//添加员工
@Options(useGeneratedKeys = true,keyProperty = "id")//获取自增长的主键值赋值给参数Emp对象的id属性
@Insert("insert into emp (username, name, gender, image, job, entrydate, dept_id, create_time, update_time)" +
"values (#{username},#{name},#{gender},#{image},#{job},#{entrydate},#{deptId},#{createTime},#{updateTime})")
public void insert(Emp emp);
} }

View File

@@ -17,7 +17,7 @@ public class Emp {
private String name;//姓名 private String name;//姓名
private Short gender;//性别 1:男 2 private Short gender;//性别 1:男 2
private String image; //头像URL private String image; //头像URL
private String job; // 职位 1:班主任 2:讲师 3:学工主管 4:教研主管 5:咨询师 private Short job; // 职位 1:班主任 2:讲师 3:学工主管 4:教研主管 5:咨询师
private LocalDate entrydate; // 入职日期 private LocalDate entrydate; // 入职日期
private Integer deptId; // 部门ID private Integer deptId; // 部门ID
private LocalDateTime createTime; private LocalDateTime createTime;

View File

@@ -1,10 +1,14 @@
package com.inmind; package com.inmind;
import com.inmind.mapper.EmpMapper; import com.inmind.mapper.EmpMapper;
import com.inmind.pojo.Emp;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import java.time.LocalDate;
import java.time.LocalDateTime;
@SpringBootTest @SpringBootTest
class SpringbootMybatisCrudApplicationTests { class SpringbootMybatisCrudApplicationTests {
@Autowired @Autowired
@@ -20,4 +24,20 @@ class SpringbootMybatisCrudApplicationTests {
System.out.println(count); System.out.println(count);
}; };
@Test
void testInsert(){
Emp emp = new Emp();
emp.setUsername("ls2");
emp.setName("李四2");
emp.setGender((short) 1);
emp.setImage("1.jpg");
emp.setJob((short) 1);
emp.setEntrydate(LocalDate.of(2005,1,1));
emp.setDeptId(1);
emp.setCreateTime(LocalDateTime.now());
emp.setUpdateTime(LocalDateTime.now());
empMapper.insert(emp);
System.out.println(emp);
System.out.println("主键id:"+emp.getId());
}
} }