Skip to content

Instantly share code, notes, and snippets.

@iseki0
Created August 5, 2023 16:28
Show Gist options
  • Save iseki0/331cd96662e7cc641cade3b638477004 to your computer and use it in GitHub Desktop.
Save iseki0/331cd96662e7cc641cade3b638477004 to your computer and use it in GitHub Desktop.
给某个群友的 Mybatis 接收 PostgreSQL array 的例子
package org.mybatis.example;
import java.util.Arrays;
import java.util.List;
public class Blog {
public int[] getArr() {
return arr;
}
public void setArr(int[] arr) {
this.arr = arr;
}
int[] arr;
@Override
public String toString() {
return "Blog{" +
"arr=" + Arrays.toString(arr) +
'}';
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultMap="aaa">
<!-- select * from Blog;-->
select '{1, 2, 3, 4}'::int[] as arr;
</select>
<resultMap id="aaa" type="org.mybatis.example.Blog" autoMapping="true">
<result column="arr" property="arr" typeHandler="space.iseki.hashutil.PGArrayInt" />
</resultMap>
</mapper>
class PGArrayInt: TypeHandler<IntArray>{
override fun setParameter(ps: PreparedStatement, i: Int, parameter: IntArray?, jdbcType: JdbcType?) {
ps.setObject(i, parameter)
}
override fun getResult(rs: ResultSet, columnName: String?): IntArray {
return (rs.getArray(columnName).array as Array<Int>).toIntArray() // 这里 PG setObject 吃 IntArray 但是 getObject 不吃,烦恼
}
override fun getResult(rs: ResultSet, columnIndex: Int): IntArray {
TODO()
}
override fun getResult(cs: CallableStatement?, columnIndex: Int): IntArray {
TODO("Not yet implemented")
}
}
fun main() {
val resource = "org/mybatis/example/mybatis-config.xml"
val inputStream: InputStream = object{}::class.java.classLoader.getResourceAsStream(resource)!!
val sqlSessionFactory = SqlSessionFactoryBuilder().build(inputStream)
sqlSessionFactory.openSession().use { session->
println(session.getMapper(BlogMapper::class.java).selectBlog())
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://127.0.0.1:5432/postgres"/>
<property name="username" value="postgres"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment