1.创建数据库表
user表
oders订单表
2.实体类
@TableName("user") 映射数据库的user表
@Data 是 Lombok 提供的一个注解,用于自动生成 Java 类中的 getter、setter、equals、hashCode 和 toString 方法
@TableId 注解来指定主键字段的名称和类型。在你的示例中,主键字段的名称被指定为 "u_id",类型为自增的 IdType.AUTO。这样配置后,MyBatis Plus 将会在进行插入操作时自动处理自增主键的生成。
@TableField 注解用于指定实体类中属性与数据库表中字段的对应关系。 @TableField(exist=false) 标记该字段不是数据库表字段
package com.example.helloworld.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.List;
@TableName ("user")
@Data
public class User {
@TableId(value = "u_id",type = IdType.AUTO)
public int userId;
public String username;
public String passwd;
@TableField(exist = false) // 标记该字段不是数据库表字段
private List<Oders> oders;
}
package com.example.helloworld.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@TableName("oders")
@Data
public class Oders {
@TableId(value = "oder_id",type = IdType.AUTO)
private int oderId;
@TableField("u_id")
private int userId;
@TableField("oder_name")
private String oderName;
@TableField("oder_price")
private double oderPrice;
}
3.建立Mapper方法
@Mapper : 将该类标记为 MyBatis 的映射器接口,告诉 Spring 在扫描时将其识别为 MyBatis 的映射器,并为其创建实例。
T selectById(Serializable id);利用继承BaseMapper的方法
这是自定义跟本例无关:
//查询所有用户
@Select("select * from user")
publicList<User> find();
@Insert("insert into user value (#{username},#{passwd}) ")
publicintinsert(Useruser);
//查询指定用户的订单列表
package com.example.helloworld.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.helloworld.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper extends BaseMapper<User> {
//查询所有用户
@Select("select * from user")
public List<User> find();
@Insert("insert into user value (#{username},#{passwd}) ")
public int insert(User user);
//查询指定用户的订单列表
}
4.建立Controller
@RestController 注解通常用于标记 Spring MVC 控制器类,指示 Spring 将其识别为 RESTful Web 服务的控制器。它是 @Controller 和 @ResponseBody 注解的组合 "/user/{id}+@PathVariable 实现传入id可变{id}相当于变量
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{id}")
public User getUserInfoById(@PathVariable int id){
User user=userService.GetUserInfoById(id);
return user;
}
}
5.建立Service
问题:调用接口类的方法会自动执行实现类重写的方法原因 这是因为在 Spring 中,通过接口注入的方式实际上是将接口的实现类注入到接口类型的引用中。当你在其他组件中注入 UserService 类型的对象时,Spring 实际上会将 UserServiceImpl 类的实例注入进去。因此,当你调用 UserService 接口的方法时,实际上调用的是 UserServiceImpl 类中的相应方法。
@Override 重写的注解
注意:在接口中只可以定义public的方法,因为接口不可实例化(自我理解)
package com.example.helloworld.service;
import com.example.helloworld.entity.User;
public interface UserService {
public User GetUserInfoById(int id);
}
package com.example.helloworld.service;
import com.example.helloworld.entity.User;
import com.example.helloworld.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User GetUserInfoById(int id) {
return userMapper.selectById(id);
}
}
6.测试
二、联合查询(一对多,一对一)
1.在实体新增List,在上面已经写了
2.数据库的表要有联系通过userid来链接
3.Mapper方法
@Results 设置返回集
@Result(property = "userId", column = "u_id"),
@Result(property = "username",column = "username"),
@Result(property = "passwd",column = "passwd")
设置映射字段property实体名column数据库字段
@Result(property="oders",javaType=List.class,column="u_id",
many= @Many(select="com.example.helloworld.mapper.OdersMapper.selectUserOdersByUserId"))
}) user表的oders属性,传递column="u_id"的id传入com.example.helloworld.mapper.OdersMapper.selectUserOdersByUserId方法
注意:使用时注意如果不定义映射,将用驼峰的方式自动转换 @Many 注解是 MyBatis 中用于处理一对多关联关系的注解之一。它通常与 @Results 注解一起使用,用于在查询结果映射中指定一个集合属性,并指定加载该集合属性的方法
package com.example.helloworld.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.helloworld.entity.Oders;
import com.example.helloworld.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper extends BaseMapper<User> {
//查询所有用户
@Select("select * from user")
public List<User> find();
@Insert("insert into user value (#{username},#{passwd}) ")
public int insert(User user);
//查询指定用户的订单列表
@Results({
@Result(property = "userId", column = "u_id"),
@Result(property = "username",column = "username"),
@Result(property = "passwd",column = "passwd"),
@Result(property = "oders", javaType = List.class, column = "u_id",
many = @Many(select = "com.example.helloworld.mapper.OdersMapper.selectUserOdersByUserId"))
})
@Select("SELECT * FROM user WHERE u_id = #{id}")
List<User> getOdersByUserId(int id);
}
@Mapper
public interface OdersMapper extends BaseMapper<OdersMapper> {
@Select("select * from oders where u_id=#{id}")
// @Result(column = "u_id",property = "userId")
List<Oders> selectUserOdersByUserId(int id);
}
4.新建Controller的getUserOdersById方法
@GetMapping("/userOders/{id}")
public List<User> getUserOdersById(@PathVariable int id){
List<User> userOders=userService.getUserOdersByUserId(id);
return userOders;
}
5.新建Service
package com.example.helloworld.service;
import com.example.helloworld.entity.Oders;
import com.example.helloworld.entity.User;
import java.util.List;
public interface UserService {
public User GetUserInfoById(int id);
public List<User> getUserOdersByUserId(int id);
}
package com.example.helloworld.service;
import com.example.helloworld.entity.Oders;
import com.example.helloworld.entity.User;
import com.example.helloworld.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User GetUserInfoById(int id) {
return userMapper.selectById(id);
}
@Override
public List<User> getUserOdersByUserId(int id) {
return userMapper.getOdersByUserId(id);
}
}
6.测试
http://localhost:9090/userOders/1
7.1对1实例一个订单只有一个用户
package com.example.helloworld.controller;
import com.example.helloworld.entity.Oders;
import com.example.helloworld.service.OdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class OdersController {
@Autowired
private OdersService odersService;
@GetMapping("/oder/{oderId}")
public List<Oders> getUserByOdersId(@PathVariable int oderId){
return odersService.getUserinfoByOderId(oderId);
}
}
package com.example.helloworld.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.helloworld.entity.Oders;
import com.example.helloworld.entity.User;
import org.apache.ibatis.annotations.*;
import java.lang.reflect.Type;
import java.util.List;
@Mapper
public interface OdersMapper extends BaseMapper<OdersMapper> {
@Select("select * from oders where u_id=#{id}")
// @Result(column = "u_id",property = "userId")
List<Oders> selectUserOdersByUserId(int id);
@Results({
@Result(property = "oderId", column = "oder_id"),
@Result(property = "uId",column = "u_id"),
@Result(property = "user", column = "u_id", javaType = User.class,
one = @One(select = "com.example.helloworld.mapper.UserMapper.selectById"))
})
@Select("Select * from Oders where oder_id=#{oderId}")
List<Oders> getUserInfoByoders(int oderId);
}
package com.example.helloworld.service;
import com.example.helloworld.entity.Oders;
import java.util.List;
public interface OdersService {
List<Oders> getUserinfoByOderId(int id);
}
package com.example.helloworld.service;
import com.example.helloworld.entity.Oders;
import com.example.helloworld.mapper.OdersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class OdersServiceImpl implements OdersService{
@Autowired
private OdersMapper odersMapper;
@Override
public List<Oders> getUserinfoByOderId(int id) {
return odersMapper.getUserInfoByoders(id);
}
}
package com.example.helloworld.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@TableName("oders")
@Data
public class Oders {
@TableId(value = "oder_id",type = IdType.AUTO)
private int oderId;
@TableField("u_id")
private int uId;
@TableField("oder_name")
private String oderName;
@TableField("oder_price")
private double oderPrice;
@TableField(exist = false)
public User user;
}
测试成功
http://localhost:9090/oder/1
三、条件构造器
1.官网条件构造器 | MyBatis-Plus
2.实例测试
//构造器测试
@GetMapping("user/find")
public List<User> findUserByAb(){
return userService.findByAb();
}
package com.example.helloworld.service;
import com.example.helloworld.entity.Oders;
import com.example.helloworld.entity.User;
import java.util.List;
public interface UserService {
public User GetUserInfoById(int id);
public List<User> getUserOdersByUserId(int id);
List<User> findByAb();
}
package com.example.helloworld.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.helloworld.entity.Oders;
import com.example.helloworld.entity.User;
import com.example.helloworld.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User GetUserInfoById(int id) {
return userMapper.selectById(id);
}
@Override
public List<User> getUserOdersByUserId(int id) {
return userMapper.getOdersByUserId(id);
}
//构造器测试
@Override
public List<User> findByAb() {
QueryWrapper queryWrapper=new QueryWrapper();
queryWrapper.eq("u_id","1");
return userMapper.selectList(queryWrapper);
}
}
swagger测试
四、分页查询
1.配置Config
package com.example.helloworld.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor paginationInterceptor(){
MybatisPlusInterceptor interceptor=new MybatisPlusInterceptor();
PaginationInnerInterceptor paginationInnerInterceptor=new PaginationInnerInterceptor(DbType.MYSQL);
interceptor.addInnerInterceptor(paginationInnerInterceptor);
return interceptor;
}
}
2.controller
//分页测试
@GetMapping("/user/findpage")
public IPage findAllpage(){
return userService.findAllPageTest();
}
3.Service
package com.example.helloworld.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.helloworld.entity.Oders;
import com.example.helloworld.entity.User;
import java.util.List;
public interface UserService {
public User GetUserInfoById(int id);
public List<User> getUserOdersByUserId(int id);
List<User> findByAb();
IPage findAllPageTest();
}
package com.example.helloworld.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.helloworld.entity.Oders;
import com.example.helloworld.entity.User;
import com.example.helloworld.mapper.UserMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User GetUserInfoById(int id) {
return userMapper.selectById(id);
}
@Override
public List<User> getUserOdersByUserId(int id) {
return userMapper.getOdersByUserId(id);
}
@Override
public List<User> findByAb() {
QueryWrapper queryWrapper=new QueryWrapper();
queryWrapper.eq("u_id","1");
return userMapper.selectList(queryWrapper);
}
@Override
public IPage findAllPageTest() {
Page<User> userPage=new Page(0,2);
IPage iPage=userMapper.selectPage(userPage,null);
return iPage;
}
}
5.测试
http://localhost:9090/user/findpage
扩展:
@Autowired于@Resource的区别:
@Autowired 和 @Resource 都是 Spring Framework 中用于进行依赖注入的注解,但它们有一些区别:
来源:
@Autowired 是 Spring 特有的注解,由 Spring 提供。
@Resource 是由 Java EE 提供的注解,Spring 对其进行了支持。
装配方式:
@Autowired 根据类型进行自动装配。当 Spring 容器发现一个需要依赖注入的属性时,它会尝试在容器中找到一个与之类型匹配的 Bean,并将其注入。
@Resource 默认按照名称进行自动装配。它会根据属性的名称在容器中查找匹配的 Bean,并将其注入。如果找不到与属性名称匹配的 Bean,则会尝试按照类型进行匹配。
属性:
@Autowired 没有额外的属性。
@Resource 可以通过指定 name 属性来指定要注入的 Bean 的名称。
支持范围:
@Autowired 可以用于构造函数、属性、方法和参数。
@Resource 主要用于属性,也可以用于 setter 方法。
导入包:
@Autowired 在 Spring 框架中使用,因此需要导入 org.springframework.beans.factory.annotation.Autowired 包。
@Resource 在 Java EE 中定义,因此需要导入 javax.annotation.Resource 包。
一般来说,推荐使用 @Autowired 注解来进行依赖注入,因为它更加灵活,并且是 Spring 框架提供的标准方式。@Resource 注解通常在需要与 Java EE 兼容或需要按名称进行装配时使用。