mybatis插入里面有个实体类字段

插入的数据时,里面包含了一个实体类字段,不知道怎么插入,请求大佬指教!

  • 下面是2个实体类
    public class Employee {
    private Integer id;
    private String lastName;
    private String email;
    private Integer gender;
    private Department department;
    private Date birth;
    private int did;
    }
    public class Department {
    private Integer id;
    private String departmentNames;
    }
  • SQL语句 但是里面含有一个department字段,不知道怎么写,请求大佬指教
  • <insert id="addEmployees" parameterType="com.pojo.Employee">

      insert into springbootdata.`employee`

    (lastName, email, gender, birth, did)

    VALUES (#{lastName}, #{email}, #{gender}, #{birth}, #{did})

    </insert>


回答:

xml文件#{department,javaType=com.alibaba.fastjson.JSONObject,typeHandler=xx.xx.xxx.dao.handler.DepartmentTypeHandler}

Handle类

@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(Department.class)
public class DepartmentTypeHandler extends BaseTypeHandler<Department> {

@Override

public Department getNullableResult(ResultSet rs, String columnName) throws SQLException {

return parseObject(rs.getString(columnName));

}

@Override

public Department getNullableResult(ResultSet rs, int i) throws SQLException {

return parseObject(rs.getString(i));

}

@Override

public Department getNullableResult(CallableStatement rs, int i) throws SQLException {

return parseObject(rs.getString(i));

}

@Override

public void setNonNullParameter(PreparedStatement ps, int i, Department object, JdbcType jdbcType) throws SQLException {

ps.setString(i, JSON.toJSONString(object));

}

private Department parseObject(String content) {

if (content == null || content.isEmpty()) {

return null;

}

try {

return JSON.parseObject(content, Department.class);

} catch (Exception e) {

throw new RuntimeException(e);

}

}

}


回答:

#{department.id}

以上是 mybatis插入里面有个实体类字段 的全部内容, 来源链接: utcz.com/p/944255.html

回到顶部