在使用MyBatis進行JSONB數據的增刪改查時,可以按照以下步驟操作:
以下是一個示例:
CREATE TABLE my_table (
id SERIAL PRIMARY KEY,
data JSONB
);
public class MyEntity {
private int id;
private String data; // JSON數據
// getters and setters
}
MyMapper.java
public interface MyMapper {
void insert(MyEntity entity);
void delete(int id);
void update(MyEntity entity);
MyEntity select(int id);
}
MyMapper.xml
<mapper namespace="com.example.MyMapper">
<insert id="insert" parameterType="com.example.MyEntity">
INSERT INTO my_table (data) VALUES (#{data})
</insert>
<delete id="delete" parameterType="int">
DELETE FROM my_table WHERE id = #{id}
</delete>
<update id="update" parameterType="com.example.MyEntity">
UPDATE my_table SET data = #{data} WHERE id = #{id}
</update>
<select id="select" parameterType="int" resultType="com.example.MyEntity">
SELECT * FROM my_table WHERE id = #{id}
</select>
</mapper>
public class Main {
public static void main(String[] args) {
try (SqlSession sqlSession = MyBatisUtil.getSession()) {
MyMapper mapper = sqlSession.getMapper(MyMapper.class);
// 插入數據
MyEntity entity = new MyEntity();
entity.setData("{\"name\": \"John\", \"age\": 30}");
mapper.insert(entity);
// 查詢數據
MyEntity result = mapper.select(entity.getId());
System.out.println(result.getData());
// 更新數據
entity.setData("{\"name\": \"Alice\", \"age\": 25}");
mapper.update(entity);
// 刪除數據
mapper.delete(entity.getId());
}
}
}
通過以上步驟,就可以利用MyBatis進行JSONB數據的增刪改查操作。在Mapper.xml文件中可以根據實際需求編寫更復雜的SQL語句來操作JSONB數據。