카테고리 없음

mybatis - postgresql

흰색남자 2023. 3. 13. 14:50

MyBatis는 자바 객체와 SQL 데이터베이스 간의 매핑을 지원하는 ORM(Object-Relational Mapping) 프레임워크 

MyBatis에서 BaseTypeHandler는 Java 타입과 SQL 데이터베이스의 타입 간의 매핑을 처리하기 위한 인터페이스

BaseTypeHandler를 상속받아 구현한 구현체는 Java 타입과 SQL 데이터베이스 간의 변환을 담당함

BaseTypeHandler를 상속받은 구현체는 다음과 같은 메서드를 구현해야 함.

setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) : Java 객체를 SQL 데이터베이스에 저장하기 위해 호출

getNullableResult(ResultSet rs, String columnName) : SQL 데이터베이스에서 결과를 읽어 Java 객체로 변환하기 위해 호출

getNullableResult(ResultSet rs, int columnIndex) : SQL 데이터베이스에서 결과를 읽어 Java 객체로 변환하기 위해 호출

getNullableResult(CallableStatement cs, int columnIndex) : SQL 데이터베이스에서 결과를 읽어 Java 객체로 변환하기 위해 호출

 

BaseTypeHandler는 Java 객체와 SQL 데이터베이스 간의 변환을 수행하기 위해 JdbcType을 사용함. JdbcType은 JDBC 타입과 연관된 상수로, Java 객체와 SQL 데이터베이스 간의 매핑에 사용.

public void setNonNullParameter(PreparedStatement ps, int i, CustomType parameter, JdbcType jdbcType) throws SQLException {
    // Java Type을 JDBC Type으로 변환하고 PreparedStatement에 설정
}

public CustomType getNullableResult(ResultSet rs, String columnName) throws SQLException {
    // ResultSet으로부터 columnName으로 CustomType 객체를 생성
}

public CustomType getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    // ResultSet으로부터 columnIndex로 CustomType 객체를 생성
}

public CustomType getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    // CallableStatement로부터 columnIndex로 CustomType 객체를 생성
}

mybatis-config.xml 파일은 다음과 같은 요소를 포함

Properties : 데이터베이스 연결 시 사용할 속성 값을 지정할 수 있는 요소입니다. Settings 요소: MyBatis의 전반적인 설정을 지정할 수 있는 요소입니다. MyBatis의 로깅 레벨, 자동 커밋 여부, 캐시 설정 등을 지정함.

TypeAliases : 복잡한 클래스명을 간결한 별칭으로 대체할 수 있는 요소

TypeHandlers : 데이터베이스와 자바 객체 간의 데이터 타입 변환을 처리하는 핸들러를 등록할 수 있는 요소

 

----

mybatis는 다음과 같은 순서로 작동함.

1. 서비스 알고리즘 단계에서 mybatis mapper를 사용한 repostiory의 메소드를 호출함.
2. repository에서 mapper를 호출함.
3. mapper에서 typehandler를 호출함.
4. typehandler의 로직을 따라감.
5. 로직을 수행 후 결과를 sql 파라미터에 적용시킴.
6. 결과를 return함

여기서 보면 알 수 있듯, sql 생성에 영향을 주는 것임. sql 결과에는 영향을 미치지 않음.

>> select문에서 integer를 string으로 바꾼다거나, User객체에서 나이를 빼와서 나이로 검색을 하던가 .. 이러한 방식으로 사용됨. 

 

 

 

mybatis mapper 파일

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.example.UserMapper">

  <select id="selectUserById" resultType="org.example.User">
    SELECT * FROM users WHERE id = #{id}
  </select>

  <insert id="insertUser" parameterType="org.example.User">
    INSERT INTO users (name, email) VALUES (#{name}, #{email})
  </insert>

  <update id="updateUser" parameterType="org.example.User">
    UPDATE users SET name = #{name}, email = #{email} WHERE id = #{id}
  </update>

  <delete id="deleteUserById" parameterType="int">
    DELETE FROM users WHERE id = #{id}
  </delete>

</mapper>

public User selectUserById(int id); 
public void insertUser(String name, String email); 
public void updateUser(int id, String name, String email); 
public void deleteUserById(int id, String name, String email);

 

<select id="withExample" parameterType="java.time.LocalDateTime" resultType="com.mybatis.test.dto.NewsDTO"> 

with tmp as ( select * from news where reg_dt > #{std} ) 
select title, journalist, publisher from tmp 

</select>

 

 

-------------- postgresql ----------------------

JSONB는 PostgreSQL에서 지원하는 데이터 타입 중 하나로, JSON 데이터를 저장하고 쿼리할 수 있는 데이터 타입. JSONB는 JSON 타입의 확장된 버전으로, 내부적으로 바이너리 형태로 저장되기 때문에 검색 속도가 빠름

JSONB는 다양한 데이터 타입을 포함할 수 있으며, 여러 계층으로 구성된 복잡한 구조를 가짐 이를 통해 JSONB 데이터를 효율적으로 저장하고 다양한 쿼리를 수행함.

JSONB 데이터를 포함하는 mytable 테이블을 생성하는 예시

CREATE TABLE mytable (
    id SERIAL PRIMARY KEY,
    data JSONB
);

INSERT INTO mytable (data) VALUES
    ('{"name": "Alice", "age": 30, "address": {"city": "New York", "state": "NY"}}'),
    ('{"name": "Bob", "age": 40, "address": {"city": "San Francisco", "state": "CA"}}'),
    ('{"name": "Charlie", "age": 50, "address": {"city": "Boston", "state": "MA"}}');

---

to_jsonb 함수와 jsonb_set 함수는 JSON 데이터를 다루는 데 유용한 함수임.

to_jsonb to_jsonb 함수는 PostgreSQL에서 제공하는 함수로, 데이터를 JSONB 형태로 변환함.이 함수는 다양한 데이터 타입을 JSONB 타입으로 변환할 수 있음

SELECT to_jsonb('hello') AS result;

-- 결과
-- {"result": "hello"}

--

SELECT to_jsonb('hello') AS result;

-- 결과
-- {"result": "hello"}

--

SELECT to_jsonb(ARRAY[1,2,3]) AS result;

-- 결과
-- {"result": [1, 2, 3]}

--

SELECT jsonb_set('{"a": 1, "b": {"c": 2}}', '{b,c}', '3', true) AS result;

-- 결과
-- {"a": 1, "b": {"c": 3}}

--

SELECT jsonb_set('{"a": 1, "b": {"c": 2}}', '{b,d}', '3', false) AS result;

-- 결과
-- ERROR:  cannot set value in non-object

JSONB는 다양한 용도로 활용함. 예를 들어, NoSQL 데이터베이스와 유사한 방식으로 JSON 데이터를 저장하고 쿼리를 실행함. 또한, JSONB 데이터를 사용하여 비정형 데이터를 저장하거나, 데이터의 일부 필드를 동적으로 추가하거나 수정할 수 있습음