weblog

技術的なメモ置き場。

Stream#collectを使用してJavaBeanリストから特定のフィールドのみを取得してリスト化する

public class Hoge {
    private String foo;
    private String bar;
    // constructor/getter/setter
}

Stream#collectを使用してHoge#barのリストを作成する。

// Hogeリストを作成
List<Hoge> hoges = Arrays.asList(new Hoge("f001", "b001")
                               , new Hoge("f002", "b002")
                               , new Hoge("f003", "b003"));
// Hoge#barのリストを作成
List<String> bars = hoges.stream().collect(ArrayList::new
                                        , (l, h) -> l.add(h.getBar())
                                        , (l1, l2) -> l1.addAll(l2));

System.out.println(bars); // [b001, b002, b003]

mapの場合

hoges.stream().map(Hoge::getBar).collect(Collectors.toList());

Spring Test DBUnitでJSONカラムにデータを投入する

Spring Test DBUnit@DatabaseSetup を使用してテストデータを投入する際に、対象のテーブルにJSONカラムが存在すると失敗するが、PostgresqlDataTypeFactoryを拡張することで投入できるようになる。

環境

  • Spring Boot 1.4.1
    • Spring Boot Test Starter
  • Spring Test DBUnit 1.3.0
  • PostgreSQL 9.5

PostgresqlDataTypeFactoryの拡張

DBUnitのFeature RequestsにJSONカラムに対応するための以下の2つのクラスが置いてある。※ステータスがpendingであることに注意
https://sourceforge.net/p/dbunit/feature-requests/188/

  • JsonType.java
  • PostgresqlDataTypeFactory.java

JSONBに対応していないので、PostgresqlDataTypeFactory.javaの一部を修正する。

public DataType createDataType(int sqlType, String sqlTypeName) throws DataTypeException {
    // 省略
    if ("json".equals(sqlTypeName) || 
        "jsonb".equals(sqlTypeName) /* ←を追加*/ ) {
            return new JsonType()
    }
    // 省略
}

Configurationクラスの修正

上の2つのクラスを適当なパッケージに配置後、Configurationクラスの修正を行う。

@Configuration
public class TestConfig {
    @Bean
    public DataSource dataSource() {
        // 省略
    }

    @Bean
    public DatabaseConfigBean dbUnitDatabaseConfig() {
        DatabaseConfigBean dbConfig = new DatabaseConfigBean();
        dbConfig.setDatatypeFactory(new PostgresqlDataTypeFactory());
        return dbConfig;
    }

    @Bean
    public DatabaseDataSourceConnectionFactoryBean dbUnitDatabaseConnection() {
        DatabaseDataSourceConnectionFactoryBean dbConnection = new DatabaseDataSourceConnectionFactoryBean(dataSource());
        dbConnection.setDatabaseConfig(dbUnitDatabaseConfig());
        return dbConnection;
    }
}

これでJSONデータの投入が可能となる。

macOSにPostgreSQLをインストール

Homebrewを使用して、macOSPostgreSQLをインストールしたので、その時の記録として残す。

環境

macOS (10.12.1) PostgreSQL (9.6.1) Homebrew (1.1.2)

Homebrewのアップデート

$ brew update
$ brew doctor

PostgreSQLのインストール

$ brew install postgresql

初期化

$ initdb /usr/local/var/postgres -E utf8

実行すると以下のようなメッセージが表示された。 指示に従って /usr/local/var/postgres を削除してから再実行。

initdb: directory "/usr/local/var/postgres" exists but is not empty
If you want to create a new database system, either remove or empty
the directory "/usr/local/var/postgres" or run initdb
with an argument other than "/usr/local/var/postgres".

/usr/local/var/postgres でエラーが発生するのは、HomebrewでPostgreSQLをインストールする際に内部でinitdbが実行されるかららしい)

今度は以下のようなワーニングが発生したが、今回はtrust認証で問題ないのでスルー。

WARNING: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.

※ trust認証については公式サイト参照。 https://www.postgresql.jp/document/9.6/html/auth-methods.html#auth-trust

起動

$ pg_ctl -D /usr/local/var/postgres -l logfile start

データベース一覧を取得してみる

$ psql -l
                              List of databases
   Name    | Owner | Encoding |   Collate   |    Ctype    | Access privileges
-----------+-------+----------+-------------+-------------+-------------------
 postgres  | admin | UTF8     | ja_JP.UTF-8 | ja_JP.UTF-8 |
 template0 | admin | UTF8     | ja_JP.UTF-8 | ja_JP.UTF-8 | =c/admin         +
           |       |          |             |             | admin=CTc/admin
 template1 | admin | UTF8     | ja_JP.UTF-8 | ja_JP.UTF-8 | =c/admin         +
           |       |          |             |             | admin=CTc/admin
(3 rows)

停止

$ pg_ctl -D /usr/local/var/postgres stop -s -m fast

本当に停止したか確認してみる

先ほどのデータベース一覧取得を再度行ってみると停止していることが分かる。

$ psql -l
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

権限設定

postgresユーザにSuperuser権限を設定する。

$ psql -U admin postgres
# ALTER ROLE postgres WITH Superuser;
# \du
                                   List of roles
 Role name |                         Attributes                         | Member of
-----------+------------------------------------------------------------+-----------
 admin     | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
 postgres  | Superuser                                                  | {}

参考

http://tstomoki.com/programming/posgre_inst http://qiita.com/_daisuke/items/13996621cf51f835494b