Value transfer between Entity objects, such as: VO object value assigned to Entity object, is a common function in code, if through get, set mutual assignment, it is very troublesome, with the utility class BeanUtils can easily complete the operation.

BeanUtils dependency package import

BeanUtils is a member of the Apache Commons component and is used to simplify encapsulating data in Javabeans. To use BeanUtils, you must import the corresponding JAR package. The Maven coordinates of BeanUtils are

< the dependency > < groupId > Commons beanutils - < / groupId > < artifactId > Commons beanutils - < / artifactId > < version > 1.9.4 < / version > </dependency>Copy the code

The sample

Assign the student ranking information (StudentVo object) from the front end to the StudentEntity and the RankingEntity respectively. These three class codes are as follows:

@Data
public class StudentVo {
    private String sno;
    private String sname;
    private Integer ranking;
    private String schoolTerm;

    public String toString(a){
        return "StudentVo object sno:"+getSno()+" sname:"+getSname()+" ranking:"+getRanking().toString()+" schoolTerm:"+getSchoolTerm(); }}@Data
public class StudentEntity {
    private String sno;
    private String sname;
    private Integer sage;

    public String toString(a){
        return "StudentEntity Object value sno:"+getSno()+" sname:"+getSname()+" sage:"+getSage(); }}@Data
public class RankingEntity {
    private String sno;
    private Integer ranking;
    private String schoolTerm;

    public String toString(a){
        return "RankingEntity Value student number of the object:"+getSno()+"Ranking:"+getRanking().toString()+Term:+getSchoolTerm(); }}Copy the code

Beanutils.copyproperties (target, source); assign the data of the source entity object to the target object. Assign only the data with the same attribute name to the target object. If the attribute in the target does not exist in the source, give null.

public class App {
    public static void main( String[] args ) throws InvocationTargetException, IllegalAccessException {
        StudentVo studentVo = new StudentVo();
        studentVo.setSno("1");
        studentVo.setRanking(20);
        studentVo.setSname("Hu Cheng");
        studentVo.setSchoolTerm("Third term");

        System.out.println(studentVo.toString());
        StudentEntity studentEntity = new StudentEntity();

        BeanUtils.copyProperties(studentEntity,studentVo);
        System.out.println(studentEntity.toString());

        RankingEntity rankingEntity = newRankingEntity(); BeanUtils.copyProperties(rankingEntity,studentVo); System.out.println(rankingEntity.toString()); }}Copy the code

Running results:

The sage attribute does not exist in StudentVo. The sage value of the studentEntity object is null