Spring Boot使用Spring Data JPA结合EntityManager实现多表关联

in 编程
关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9

表格(Table)

简单的数据格式

DROP TABLE IF EXISTS `my_order`;
CREATE TABLE `my_order` (
  `order_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `code` varchar(50) NOT NULL,
  PRIMARY KEY (`order_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of my_order
-- ----------------------------
INSERT INTO `my_order` VALUES ('1', '1', '123456');
INSERT INTO `my_order` VALUES ('2', '1', '654321');
INSERT INTO `my_order` VALUES ('3', '2', '12345678');
INSERT INTO `my_order` VALUES ('4', '2', '87654321');
-- --------------------------------------------------------
DROP TABLE IF EXISTS `my_user`;
CREATE TABLE `my_user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of my_user
-- ----------------------------
INSERT INTO `my_user` VALUES ('1', 'biz');
INSERT INTO `my_user` VALUES ('2', 'ord');

实体(Entity)

为了保持简单,从最简单常用的实体开始:用户(MyUser)和订单(MyOrder)

@Entity
public class MyUser {
    private int userId;
    private String name;

    @Id
    @Column(name = "user_id")
    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    @Basic
    @Column(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MyUser user = (MyUser) o;
        return userId == user.userId &&
                Objects.equals(name, user.name);
    }

    @Override
    public int hashCode() {

        return Objects.hash(userId, name);
    }
}
@Entity
public class MyOrder {
    private int orderId;
    private int userId;
    private String code;

    @Id
    @Column(name = "order_id")
    public int getOrderId() {
        return orderId;
    }

    public void setOrderId(int orderId) {
        this.orderId = orderId;
    }

    @Basic
    @Column(name = "user_id")
    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    @Basic
    @Column(name = "code")
    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MyOrder order = (MyOrder) o;
        return orderId == order.orderId &&
                userId == order.userId &&
                Objects.equals(code, order.code);
    }

    @Override
    public int hashCode() {

        return Objects.hash(orderId, userId, code);
    }
}

DAO层

映射实体操作数据库

public interface EntityManagerDao<T> {

    List<T> findByJPQL(String jpql);

    List<T> findByJPQL(String jpql, int page, int pageSize);

}
@Repository  //重点
public class EntityManagerDaoImpl<T> implements EntityManagerDao<T> {

    @PersistenceContext //重点
    private EntityManager entityManager;

    @Override
    public List<T> findByJPQL(String jpql) {
        Query query = entityManager.createQuery(jpql);
        List<T> list = query.getResultList();
        entityManager.close();
        return list;
    }


    @Override
    public List<T> findByJPQL(String jpql, int page, int pageSize) {
        if (page < 1) {
            page = 1;
        }
        if (pageSize < 1) {
            pageSize = 10;
        }
        Query query = entityManager.createQuery(jpql);
        query.setFirstResult((page - 1) * pageSize);
        query.setMaxResults(pageSize);
        List<T> list = query.getResultList();
        return list;
    }

}

展示数据格式(VO)

public class OrderUser implements Serializable {
    private static final long serialVersionUID = 1L;

    private String code;

    private MyUser user;

    public OrderUser() {
    }

    public OrderUser(String code, MyUser user) {
        this.code = code;
        this.user = user;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public MyUser getUser() {
        return user;
    }

    public void setUser(MyUser user) {
        this.user = user;
    }

}

Service层

连接Controller层与Dao层,对外传输展示数据,可实现事务控制

public interface OrderUserService {

    List<OrderUser> getOrderUser();
}
@Service  //重点
//@Transactional //开启事务
public class OrderUserServiceImpl implements OrderUserService {

    @Autowired //重点
    EntityManagerDao<OrderUser> entityManagerDao;

    @Override
    public List<OrderUser> getOrderUser() {
        String jpql = "select new demo.springboot.entity.OrderUser(o.code,u) from MyOrder as o ,MyUser as u where o.userId = u.userId";

        // 方式一,无分页
        // List<OrderUser> list = entityManagerDao.findByJPQL(jpql);

        // 方式二,分页(此处偷懒,没有分开实现,也没有传输分页参数)
        List<OrderUser> list = entityManagerDao.findByJPQL(jpql, 1, 2);
        return list;
    }
}

Controller层

后端与前端数据交互

@RestController
@RequestMapping("/order-user")
public class OrderUserController {

    @Autowired
    OrderUserService orderUserService;

    @GetMapping("/get")
    public List<OrderUser> getOrderUser() {
        List<OrderUser> list = orderUserService.getOrderUser();
        return list;
    }
}

前端数据测试

启动服务,在地址栏输入:http://localhost:8080/order-user/get

结果展示

{
    "code": "123456",
    "user": {
        "userId": 1,
        "name": "biz"
    },
    "code": "654321",
    "user": {
        "userId": 1,
        "name": "biz"
    }
}

以上, 希望大家一起学习,交流

学习参考:

https://blog.csdn.net/linzhiqiang0316/article/details/53022683

https://blog.csdn.net/sunshuolei/article/details/48050491

https://blog.csdn.net/czp11210/article/details/50799489

关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9
扫一扫关注公众号添加购物返利助手,领红包
Comments are closed.

推荐使用阿里云服务器

超多优惠券

服务器最低一折,一年不到100!

朕已阅去看看