Browse Source

新增Set 支持

zhouhao 8 years ago
parent
commit
f111d0cfd0

+ 79 - 0
hsweb-commons/hsweb-commons-dao/hsweb-commons-dao-mybatis/src/main/java/org/hswebframework/web/dao/mybatis/handler/JsonSetHandler.java

@@ -0,0 +1,79 @@
+/*
+ *  Copyright 2016 http://www.hswebframework.org
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ *
+ */
+
+package org.hswebframework.web.dao.mybatis.handler;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.serializer.SerializerFeature;
+import org.apache.ibatis.type.*;
+
+import java.sql.CallableStatement;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.HashSet;
+import java.util.Set;
+
+@Alias("jsonSetHandler")
+@MappedTypes({Set.class})
+@MappedJdbcTypes({JdbcType.VARCHAR, JdbcType.CLOB})
+public class JsonSetHandler extends BaseTypeHandler<Set<Object>> {
+
+    @Override
+    public Set<Object> getResult(ResultSet rs, int columnIndex) throws SQLException {
+        String s = rs.getString(columnIndex);
+        return new HashSet<>(JSON.parseArray(s));
+    }
+
+    @Override
+    public Set<Object> getResult(ResultSet rs, String columnName) throws SQLException {
+        String s = rs.getString(columnName);
+        return new HashSet<>(JSON.parseArray(s));
+    }
+
+    @Override
+    public Set<Object> getResult(CallableStatement cs, int columnIndex) throws SQLException {
+        String s = cs.getString(columnIndex);
+        return new HashSet<>(JSON.parseArray(s));
+    }
+
+    @Override
+    public void setParameter(PreparedStatement ps, int i, Set<Object> parameter, JdbcType jdbcType) throws SQLException {
+        ps.setString(i, JSON.toJSONString(parameter, SerializerFeature.WriteClassName));
+    }
+
+    @Override
+    public void setNonNullParameter(PreparedStatement ps, int i, Set<Object> parameter, JdbcType jdbcType) throws SQLException {
+        ps.setString(i, "[]");
+    }
+
+    @Override
+    public Set<Object> getNullableResult(ResultSet rs, String columnName) throws SQLException {
+        return new HashSet<>();
+    }
+
+    @Override
+    public Set<Object> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
+        return new HashSet<>();
+    }
+
+    @Override
+    public Set<Object> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
+        return new HashSet<>();
+    }
+}