springmvc - java如何封装多个不同的实体
黄舟
黄舟 2017-04-18 10:41:22
0
3
596
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(3)
左手右手慢动作

Another layer of encapsulation,
The class name should be related to the business

public class UserAndCustomerVo{

    private User user;
    
    private Customer customer;

    //getter setter method
}
@RequestMapping("test")
public UserAndCustomerVo getSomeInfo() {
    User user = new User();
    Customer customer = new Customer();
    UserAndCustomerVo uacVo = new UserAndCustomerVo();
    uacVo.setUser(user);
    uacVo.setCustomer(customer);

    return uacVo;
}

This way you can continue to add more if your business needs to expand in the future

迷茫

I think it’s simpler and better to use Map. If the data you want to pass has a clear type, it seems that you can only define the type or interface yourself. However, if it is used to convert to JSON, it would be better to use Map.

In addition, you can also use anonymous classes,

class User {
    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }
    private String name;

    public int getAge() {
        return age;
    }
    private int age;
}

class Customer {
    public Customer(String name, double money) {
        this.name = name;
        this.money = money;
    }

    public String getName() {
        return name;
    }
    private String name;

    public double getMoney() {
        return money;
    }
    private double money;
}

public class Test extends Thread {
    public static void main(String[] args) {
        final User _user = new User("James", 30);
        final Customer _customer = new Customer("Andy", 100.00);

        // 匿名类实现组合类型
        Object combine = new Object() {
            {
                this.user = _user;
                this.customer = _customer;
            }

            private User user;
            private Customer customer;

            public User getUser() {
                return user;
            }

            public Customer getCustomer() {
                return customer;
            }

            public String toString() {
                return user.getName() + "|" + customer.getName();
            }
        };

        System.out.println(combine.toString());
    }
}

If you need a clear interface, you can customize an interface and replace new Object() { .... } 中那个 Object in the code with your own interface - but if it is so troublesome to write, you can define a combination type yourself. You can research custom Tuple generics yourself (it seems you can also search them online).

阿神

Personally, I think Map is better accepted, Map<String, List<Model>>, just a few bean classes and a few lists are put into Map

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template