一.常用注解以及配置文件
核心配置文件
<!--加载映射关系 TODO-->
<mappers>
<!--指定接口所在的包-->
<package name="com.itheima.mapper"/>
</mappers>
二.基本的CRUD
编写接口类 使用注解实现sql语句
public interface UserMapper {
@Insert("insert into user values(#{id},#{username},#{password},#{birthday})")
public void save(User user);
@Update("update user set username=#{username},password=#{password} where id=#{id}")
public void update(User user);
@Delete("delete from user where id=#{id}")
public void delete(int id);
@Select("select * from user where id=#{id}")
public User findById(int id);
@Select("select * from user")
public List<User> findAll();
}
三.复杂的映射开发
1.一对一查询
引入之前的Order实体
select *,o.id oid from orders o,user u where o.uid=u.id
映射封装
方法1:
@Select("select *,o.id oid from orders o,user u where o.uid=u.id")
@Results({
@Result(column = "oid",property = "id"),
@Result(column = "ordertime",property = "ordertime"),
@Result(column = "total",property = "total"),
@Result(column = "uid",property = "user.id"),
@Result(column = "username",property = "user.username"),
@Result(column = "password",property = "user.password")
})
public List<Order> findAll();
方法2:调用其他接口的方法进行二次查询封装
@Select("select * from orders")
@Results({
@Result(column = "oid",property = "id"),
@Result(column = "ordertime",property = "ordertime"),
@Result(column = "total",property = "total"),
@Result(
property = "user", //要封装的属性名称
column = "uid",//根据哪个字段去查询user表的数据 传递过去的参数
javaType = User.class, //要封装的实体类型 返回值
//select属性 代表查询哪个接口的方法获得数据 调用方法
one = @One(select = "com.itheima.mapper.UserMapper.findById")
)
})
public List<Order> findAll();
2.一对多
1.User添加OrderList属性
2.OrderMapper添加:根据用户id查询订单
@Select("select * from orders where uid=#{uid}")
public List<Order> findByUid(int uid);
3.UserMapper:调用OrderMaper接口findByUid方法二次查询
@Select("select * from user")
@Results({
@Result(id = true,column = "id",property = "username"),
@Result(column = "username",property = "username"),
@Result(column = "password",property = "password"),
@Result(
property = "orderList",
column = "id",
javaType = List.class,
many = @Many(select = "com.itheima.mapper.OrderMapper.findByUid")
)
})
public List<User> findUserAndOrderAll();
3.多对多
1.引入之前的Role实体
2.User加入RoleList
3.RoleMapper实现根据用户Id查找角色方法
public interface RoleMapper {
@Select("select * from sys_user_role ur,sys_role r where ur.roleId=r.id AND ur.userId=#{id}")
public List<Role> findByUid(int id);
}
4.UserMapper
@Select("select * from User")
@Results({
@Result(id = true,column = "id",property = "username"),
@Result(column = "username",property = "username"),
@Result(column = "password",property = "password"),
@Result(
property = "roleList",
column = "id",
javaType = List.class,
many = @Many(select = "com.itheima.mapper.RoleMapper.findByUid")
)
})
public List<User> findUserAndRoleAll();