MyBatis注解完成增删改查

作者: adm 分类: java,mybatis,mysql 发布时间: 2023-07-28

使用注解开发会比配置文件开发更加方便

@Select("select * from tb_user where id = #(id)")
public User selectByld(int id);
查询:@Select

添加:@Insert

修改:@Update

删除:@Delete

提示:

注解完成简单功能

配置文件完成复杂功能

下面使用注解完成一个查询的功能

在UserMapper.java的接口文件中添加接口

    /*
    *使用注解完成简单的查询功能
    *  */
    @Select("select * from tb_user where id = #{id}")
    User selectById(int id);

1.一对一
一个员工对应一个部门: 查询一个员工,同时把他的部门查询出来

EmpDao

@Select("select * from t_emp e left join t_dept d on e.emp_id = d.d_id"+ 
        "where e.emp_id = #{empId}")
@Results(value = {
        @Result(id = true, column = "emp_id", property = "empId"),
        @Result(column = "emp_name", property = "empName"),
        @Result(column = "emp_salary", property = "empSalary"),
        @Result(column = "emp_age", property = "empAge"),
   						 //根据查询结果列名d_id,去查询部门,再把结果设置给emp的部门属性
        @Result(column = "d_id",property = "dept", 
                one = @One(select = "com.zzhua.dao.DeptDao.selectById",
                           fetchType = FetchType.EAGER))
})
Emp selectById(Integer empId);

DeptDao

@Select("select * from t_dept where d_id = #{id}")
@Results({
        @Result(id = true,column = "d_id",property ="dId"),
        @Result(id = true,column = "d_name",property ="dName")
})
Dept selectById(@Param("id") Integer id);

测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:application.context-dao.xml"})
public class SpringTest {

    @Autowired
    private EmpDao empDao;

    @Test
    public void test05(){
        Emp emp = empDao.selectById(1);
        System.out.println(emp);
    }
}

2.一对多
一个部门对应多个员工:查询部门,同时把这个部门下的所有员工查询出来
DeptDao

@Select("select * from t_dept where d_id = #{id} ")
@Results({
        @Result(id = true,column = "d_id",property = "dId"),
        @Result(column = "d_name",property = "dName"),
        @Result(column = "d_id",property = "empList",
                
                many = @Many(select = "com.zzhua.dao.EmpDao.selectEmpsByDid",
                             fetchType = FetchType.EAGER))
})
Dept selectById(@Param("id") Integer id);
EmpDao

@Select("select * from t_emp where d_id = #{id} ")
@Results({
        @Result(id = true, column = "emp_id", property = "empId"),
        @Result(column = "emp_name", property = "empName"),
        @Result(column = "emp_salary", property = "empSalary"),
        @Result(column = "emp_age", property = "empAge")
})
List selectEmpsByDid(@Param("id") Integer id);

测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:application.context-dao.xml"})
public class SpringTest {

    @Autowired
    private DeptDao deptDao;

    @Test
    public void test05(){
        Dept dept = deptDao.selectById(1);
        System.out.println(dept);
    }
}

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!