Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map Enum type in mybatis using typeHandler on insert

I have strugled with enum for a while now but it will not go my way. Is there anyone that can give me hint? I am trying to use Enum type in MySql and I also use an Enum class in my code.

As the code is now It will insert MONDAY but it will also try to insert MONDAY on workdayID... I do not get the workdayID. I belive I have to handle the DAY_TYPE in som way ... define a typeHandler maybe?? but I tried that and it would not work, or its becouse I can not do it correct?

I also tried the org.apache.ibatis.type.EnumTypeHandler but with no success, like this

    #{DAY_TYPE,typeHandler=org.apache.ibatis.type.EnumTypeHandler}

DAY_TYPE.java

    package tut.model;
    import java.io.Serializable;
    public enum DAY_TYPE implements Serializable{
        MONDAY(1),TUESDAY(2),WEDNESDAY(3),THURSDAY(4),FRIDAY(5),SATURDAY(6),SUNDAY(7);
        private int id; private int workdayID;

        private DAY_TYPE(int id) { this.id = id; }

        public int getId() { return id;    }
        public void setId(int id) {  this.id = id;    }

        public int getWorkdayID() { return workdayID;    }
        public void setWorkdayID(int workdayID) {this.workdayID = workdayID;}
    }

DAY_TYPE_Mapper.xml

    <insert id="insert" parameterType="DAY_TYPE" useGeneratedKeys="true" keyProperty="iddaytaype">
        INSERT INTO daytaype (DAY_TYPE, workdayID)
        VALUES (#{DAY_TYPE},#{workdayID})
        <selectKey keyProperty="iddaytaype" resultType="long" order="AFTER">
            SELECT LAST_INSERT_ID();
        </selectKey>
    </insert>

<!-- <insert id="insert" parameterMap="insert-params" useGeneratedKeys="true" keyProperty="iddaytaype"> -->
    <parameterMap id="insert-params"   type="DAY_TYPE">
        <parameter property="DAY_TYPE" javaType="DAY_TYPE" typeHandler="mappings.XenumTypeHandler"  />
        <parameter property="workdayID" javaType="int" />
    </parameterMap>  

My database table

    CREATE TABLE `daytaype` (
      `iddaytaype` int(11) NOT NULL AUTO_INCREMENT,
      `DAY_TYPE` enum('MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY','SUNDAY') NOT NULL,
      `workdayID` int(11) unsigned DEFAULT NULL,
      PRIMARY KEY (`iddaytaype`),
      KEY `fk_workDayID_idWorkDay` (`workdayID`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;=InnoDB DEFAULT CHARSET=utf8;      
like image 972
user2279869 Avatar asked Apr 14 '13 15:04

user2279869


1 Answers

override getter setter. my like this:

@Column(name = "type")
private MailType type;

public String getType(){
    return type.name();
}
public void setType(String type){
    this.type = MailType.valueOf(type);
}
public MailType getTypeEnum(){
    return type;
}
public void setTypeEnum(MailType type){
    this.type = type;
}
like image 120
Jacky.cheng Avatar answered Sep 26 '22 15:09

Jacky.cheng