使用BeanUtil.tobean()方法和@Accessors注解将两个表的数据同时查询出来

今天在做查询的时候,突然想到不使用关联查询能不能同时将两个表的数据给查询出来,于是我就问了一个大佬,这是那位大佬的博客,大家有兴趣也可以去看看。http://t.csdn.cn/uwNWOicon-default.png?t=N7T8http://t.csdn.cn/uwNWO还真有一个方法,详细如下:

先创建两个实体类

Product类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product {
    private int id;
    private  String name;
    private float price;
    private  String description;
    private int category_id;




}

Category类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Category {
    private int id;
    private  String name;
    private List<Product> productList;

}

ProductVO类(value object值对象,通常用于业务层之间的数据传递) 继承于Product类

@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class productVo extends Product{
    private  String categoryName;
}

@Accessors注解

该注解主要作用是:当属性字段在生成 getter 和 setter 方法时,做一些相关的设置。

chain属性:不写默认为false,当该值为 true 时,对应字段的 setter 方法调用后,会返回当前对象

Mapper层(不作描述,大家都懂)

     @Select("select * from product where id=#{id}")
     Product findbyId(@Param("id") Long id);



     @Select("select * from category where id=#{categoryId}")
     Category findbyProductId(@Param("categoryId") int categoryId);

Service层(两个接口哈,别搞错了,懒得分开复制了)

public interface CategoryService {
    Category findbyProductId(int categoryId);
}

public interface ProductService {


    productVo findbyId(Long id);


}

CategoryServiceImpl类(实现CategoryService接口,调用Mapper层的查询方法)

public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Override
    public Category findbyProductId(int categoryId) {


        return categoryMapper.findbyProductId(categoryId);
    }
}

ProductServiceImpl类(实现ProductService接口)骚操作在这里

@Autowired
private ProductMapper productMapper;

@Autowired
private CategoryService categoryService; 
@Override
    public productVo findbyId(Long id) {

        Product product=productMapper.findbyId(id);

        if (product==null){
            throw new RuntimeException("查询失败");
        }
        Category category=categoryService.findbyProductId(product.getCategory_id());

        productVo vo = BeanUtil.toBean(product, productVo.class);



        return vo.setCategoryName(category.getName());
    }

没有注释,就由我在这里解释了,

Product product=productMapper.findbyId(id);
Category category=categoryService.findbyProductId(product.getCategory_id());

这两句大家都懂,根据id将查询的数据封装到一个对象中,那么,重点来了

BeanUtil.toBean()方法

在Hutool工具包中,BeanUtil类的toBean()方法用于将一个对象或Map转换成指定类型的JavaBean对象。我们先创建了一个数据源对象product,然后,通过调用BeanUtil.toBean()方法,将数据源对象product转换成目标类型 productVo的JavaBean对象vo。

至于最后的返回值,在上面使用了@Accessors(chain = true)注解,使用setter方法,返回当前对象。

需要注意的是,转换过程中,BeanUtil.toBean()方法通过反射机制创建了目标类型的实例,并将数据源对象的属性值复制到目标对象中。所以,需要保证数据源对象和目标类型的属性名称和类型保持一致,否则无法正确转换属性值。所以在创建ProductVo时,是继承于Product的。另外,还需要在项目中引入Hutool的相关依赖才能使用BeanUtil类的方法。

    <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.17</version>
        </dependency>

最后,创建一个接口来测试一下吧


@RestController
@RequestMapping("/product")
public class ProductController {


    @Autowired
    private ProductService productService;


    
      @GetMapping
    public productVo findbyId(Long id){

        return productService.findbyId(id);
      }




6153900b1d9b4663b8a67d30fa1c7644.png

成功了!!

第一次写博客,也是一个比较简单的案例,希望大家多多支持。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
BeanUtils.toBean方法是Apache Commons BeanUtils库中的一个方法,用于将一个Map对象转换为一个Java Bean对象。该方法可以根据Map中的键值对将对应的属性值设置到Java Bean对象中。 下面是一个示例代码,演示了如何使用BeanUtils.toBean方法将Map对象转换为Java Bean对象: ```java import org.apache.commons.beanutils.BeanUtils; import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Map<String, Object> map = new HashMap<>(); map.put("name", "John"); map.put("age", 25); map.put("birthday", "1995-01-01"); try { Person person = (Person) BeanUtils.toBean(map, Person.class); System.out.println(person.getName()); // 输出:John System.out.println(person.getAge()); // 输出:25 System.out.println(person.getBirthday()); // 输出:1995-01-01 } catch (Exception e) { e.printStackTrace(); } } } class Person { private String name; private int age; private java.sql.Date birthday; // 省略getter和setter方法 } ``` 在上面的示例中,我们创建了一个Map对象,其中包含了name、age和birthday三个属性的键值对。然后使用BeanUtils.toBean方法将该Map对象转换为Person对象,并输出了Person对象的属性值。 需要注意的是,如果Map中的属性值是String类型,而Java Bean中对应的属性是Date类型,那么在转换过程中可能会出现转换异常的错误。为了解决这个问题,可以使用BeanUtils注册一个日期转换器,将String类型的日期转换为java.sql.Date类型。具体的注册方法可以参考Apache Commons BeanUtils的文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值