6 - TypeHandler-2

本小节对枚举类型进行转换
table

create table `student`(
`id` int auto_increment primary key,
`name` varchar(30) not null,
`age` int,
`gender` int default 0
)auto_increment=10000;

enum

package model;

public enum GenderEnum {
    MALE("男",0),FEMALE("女",1),UNKNOW("不知道",2);
    private String gender;
    private int code;
    GenderEnum(String gender, int code){
        this.gender = gender;
        this.code = code;
    }
    public static GenderEnum getGender(String genderName){
        for (GenderEnum gender: GenderEnum.values()){
            if(gender.gender.equalsIgnoreCase(genderName)){
                return gender;
            }
        }
        return null;
    }

    public static GenderEnum getGender(int code){
        for (GenderEnum gender: GenderEnum.values()){
            if(gender.code == code){
                return gender;
            }
        }
        return null;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getCode() {
        return code;
    }

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

    @Override
    public String toString() {
        return "GenderEnum{" +
                "gender='" + gender + '\'' +
                ", code=" + code +
                '}';
    }
}

model

package model;

public class Student {
    private int id;
    private String name;
    private int age;

    private GenderEnum gender;

    public Student() {
    }
    //getter setter
 }

dao

public interface StudentMapper {
    int insertStudent(Student student);
    Student selectStudentById(int id);
}

mapper
这里的typeHandler使用了别名

 
      insert into `student`(`name`,`age`,`gender`)
      values(#{name},#{age},#{gender,typeHandler=genderTypeHandler})
      
          select last_insert_id();
      
    

    
        
        
        
        
    

    

test


你可能感兴趣的:(6 - TypeHandler-2)