創建
CREATE TABLE faviroute_book (
id serial primary key,
student_names TEXT[]
)
在普通類型後面加 [] 即可
插入
-- 方式一 使用{}
insert into student(student_names) values ('{阿離,小奏}')
-- 方式二 使用 array
insert into student(student_names) VALUES (array['韓信','關羽','張飛'])
查詢
select * from student
select student_names[2] from student
刪除
delete from student where student_names[3] = '張飛'
delete from student where id = 3
更新
update student set student_names[1] = '阿離' where id = 1
update student set student_names[3] = '李白' where id = 1
Mybatis中的使用
第一種更新操作比較容易, 自己拼接下標
update student
set student_names[#{index}] = #{name}
where
id= #{id}
第二種自定義數組類型
創建 ArrayTypeHandler
@MappedJdbcTypes(JdbcType.ARRAY)
@MappedTypes(String[].class)
public class ArrayTypeHandler extends BaseTypeHandler<Object[]> {
private static final String TYPE_NAME_VARCHAR = "varchar";
private static final String TYPE_NAME_INTEGER = "integer";
private static final String TYPE_NAME_BOOLEAN = "boolean";
private static final String TYPE_NAME_NUMERIC = "numeric";
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Object[] parameter, JdbcType jdbcType) throws SQLException {
String typeName = null;
if (parameter instanceof Integer[]) {
typeName = TYPE_NAME_INTEGER;
} else if (parameter instanceof String[]) {
typeName = TYPE_NAME_VARCHAR;
} else if (parameter instanceof Boolean[]) {
typeName = TYPE_NAME_BOOLEAN;
} else if (parameter instanceof Double[]) {
typeName = TYPE_NAME_NUMERIC;
}
if (typeName == null) {
throw new TypeException("ArrayTypeHandler parameter typeName error, your type is " + parameter.getClass().getName());
}
// 這3行是關鍵的代碼,創建Array,然後ps.setArray(i, array)就可以了
Connection conn = ps.getConnection();
Array array = conn.createArrayOf(typeName, parameter);
ps.setArray(i, array);
}
@Override
public Object[] getNullableResult(ResultSet resultSet, String s) throws SQLException {
return getArray(resultSet.getArray(s));
}
@Override
public Object[] getNullableResult(ResultSet resultSet, int i) throws SQLException {
return getArray(resultSet.getArray(i));
}
@Override
public Object[] getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
return getArray(callableStatement.getArray(i));
}
private Object[] getArray(Array array) {
if (array == null) {
return null;
}
try {
return (Object[]) array.getArray();
} catch (Exception e) {
}
return null;
}
}
使用
List<Student> updateNames(@Param("id") Integer id,@Param("names") Integer... names);
<update id="updateNames">
update student
set student_names= #{names,typeHandler = com.sinoxk.drug.config.ArrayTypeHandler}
where
id= #{id}
</update>