如何在插入时使用 typeHandler 映射 mybatis 中的 Enum 类型
2022-09-04 22:25:11
我已经用枚举纠缠了一段时间,但它不会按照我的方式进行。有没有人可以给我提示?我正在尝试在MySql中使用Enum类型,并且我还在我的代码中使用Enum类。
由于代码现在是它将插入星期一,但它也将尝试在工作日ID上插入星期一...我没有收到工作日ID。我相信我必须以索姆的方式处理DAY_TYPE...定义一个类型处理程序也许??但是我试过了,它不会起作用,或者它的becouse我不能做正确的事情?
我也尝试了org.apache.ibatis.type.EnumTypeHandler,但没有成功,就像这样
#{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>
我的数据库表
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;