tsalakh ain sus noam Huyah ol guf

勉強会のメモ。その他備忘録。参考にさせて頂いたサイトや資料はリンクさせて頂いていますが不都合があればご連絡ください。

【技術メモ】SpringBootからPostgresに繋ぐ

SpringBootからPostgresに繋ぐ

概要

詳細

postgres

postgres=> create database testdb;
postgres=>\c testdb;
postgres=> create schema testschema;
postgres=> set search_path to testschema;
postgres=> create table test_data ( id serial, data varchar(200), primary key (id) );
postgres=> insert into test_data values ( default, 'data1');
postgres=> insert into test_data values ( default, 'data2');
postgres=> insert into test_data values ( default, 'data3');

設定ファイル

pom.xml

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

application.properties

spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/testdb
spring.datasource.username=postgres
spring.datasource.password=password
spring.jpa.properties.hibernate.default_schema=testschema

hibernate.properties

「PostgresにCLOBが見つかりません」の起動時エラーを防ぐ

hibernate.jdbc.lob.non_contextual_creation=true

Java

Entityクラス

@Entity
@Table(name = "test_data")
@Data
public class TestData {

  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private int id;

  @Column(name="data")
  private String data;
}

Repositoryインタフェース

@Repository
public interface TestDataRepository extends JpaRepository<TestData,Integer> {

}

Serviceクラス

@Service
@Transactional
public class TestDataCrudService {

    @Autowired
    TestDataRepository repository;
    
    public List<String> getTestData() {
        List<String> ret = new ArrayList<>();
        repository.findAll().forEach(data -> ret.add(data.getData()));
        return ret;
    }
}

参考リンク

link Spring Boot + PostgreSQLの設定方法