sql—通过调用java方法为h2数据库中的新行生成默认值

hmtdttj4  于 2021-07-08  发布在  Java
关注(0)|答案(2)|浏览(257)

生成测试数据时,我希望新行中的字段默认为lorem生成的gibberish值,lorem是一个用于java的loremipsum生成器。
在java中调用lorem工具如下所示:

String lorem = LoremIpsum.getInstance().getWords( 100 , 120 );

我尝试使用以下sql作为表定义:

String sql =
        """
        CREATE ALIAS LOREM FOR "com.thedeanda.lorem.LoremIpsum.getInstance().getWords( 100 , 120 )";
        CREATE TABLE IF NOT EXISTS thing_
        (
            nonsense_ text NOT NULL  ,
            row_created_ TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP() ,
            id_ uuid NOT NULL DEFAULT RANDOM_UUID() ,
            CONSTRAINT thing_pkey_ PRIMARY KEY ( id_ )
        )
        ;
        """;

但这意味着:
org.h2.jdbc.jdbcsqlsyntaxerrorexception:未找到公共静态java方法:“getinstance().getwords(100120)(com.thedeanda.lorem.loremipsum)”;sql语句:
为“com.thedeanda.lorem.loremipsum.getinstance().getwords(100120)”创建别名lorem[90139-200]
是否有某种方法可以 Package 对java方法的调用,将其用作SQLforH2中的函数?

91zkwejq

91zkwejq1#

我认为不能包含参数,也不能调用示例方法。您需要创建一个静态方法:

public class Whatever {
    public static String generateLorem() {
        return LoremIpsum.getInstance().getWords(100, 120);
    }
}

然后

CREATE ALIAS LOREM FOR "com.foo.Whatever.generateLorem";
bkhjykvo

bkhjykvo2#

rzwitserloot的回答是正确的。
此外,下面是一个完整的示例应用程序,演示了在该答案中看到的方法。
要运行此代码,请替换调用中的file path参数 ds.setURL 根据您的喜好命名和放置数据库文件。然后运行 main 方法。

package work.basil.example;

import com.thedeanda.lorem.LoremIpsum;
import org.h2.jdbcx.JdbcDataSource;

import javax.sql.DataSource;
import java.sql.*;
import java.time.*;

import java.util.Objects;
import java.util.UUID;

public class FiftyMillion
{
    DataSource dataSource;

    public static String generateLorem ( )
    {
        return LoremIpsum.getInstance().getWords( 100 , 120 );
    }

    public static void main ( String[] args )
    {
        FiftyMillion app = new FiftyMillion();

        app.prepareDatabase();
        app.makeRow();
        app.dumpRows();
//        app.populateDatabase();
//        app.exportDatabaseToCsv();
    }

    // Constructor
    public FiftyMillion ( )
    {
        // DataSource
        org.h2.jdbcx.JdbcDataSource ds = Objects.requireNonNull( new JdbcDataSource() );  // Implementation of `DataSource` bundled with H2.
        ds.setURL( "jdbc:h2:/Volumes/blue_disc/fifty_million;" );
        ds.setUser( "scott" );
        ds.setPassword( "tiger" );
        ds.setDescription( "An example database showing ResultSet access to 50 million records." );
        this.dataSource = ds;
    }

    private void prepareDatabase ( )
    {
        String lorem = LoremIpsum.getInstance().getWords( 100 , 120 );
        String sql =
                """
                CREATE ALIAS IF NOT EXISTS LOREM FOR "work.basil.example.FiftyMillion.generateLorem" ;
                CREATE TABLE IF NOT EXISTS thing_
                (
                    nonsense_ text NOT NULL DEFAULT LOREM() ,
                    row_created_ TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP() ,
                    id_ uuid NOT NULL DEFAULT RANDOM_UUID() ,
                    CONSTRAINT thing_pkey_ PRIMARY KEY ( id_ )
                )
                ;
                """;
        try (
                Connection conn = dataSource.getConnection() ;
                Statement stmt = conn.createStatement() ;
        )
        {
            System.out.println( "INFO - Running `prepareDatabase` method." );
            stmt.executeUpdate( sql );
        }
        catch ( SQLException e )
        {
            e.printStackTrace();
        }
    }

    private void makeRow ( )
    {
        try
                (
                        Connection conn = this.dataSource.getConnection() ;
                        Statement stmt = conn.createStatement() ;
                )
        {
//            String lorem = LoremIpsum.getInstance().getWords( 100 , 120 );
            String sql =
                    """
                    INSERT INTO thing_ ()
                    VALUES ()
                    ;
                    """;
            stmt.executeUpdate( sql );
        }
        catch ( SQLException e )
        {
            e.printStackTrace();
        }
    }

    private void dumpRows ( )
    {
        try
                (
                        Connection conn = this.dataSource.getConnection() ;
                        Statement stmt = conn.createStatement() ;
                )
        {
            String sql =
                    """
                    TABLE thing_
                    ;
                    """;
            stmt.executeQuery( sql );
            ResultSet rs = stmt.executeQuery( sql );
            while ( rs.next() )
            {
                String nonsense = rs.getString( "nonsense_" );
                Instant whenCreated = rs.getObject( "row_created_" , OffsetDateTime.class ).toInstant();
                UUID id = rs.getObject( "id_" , UUID.class );
                System.out.println( "whenCreated = " + whenCreated + " | " + "id : " + id + " | " + "nonsense = " + nonsense );
            }
        }
        catch ( SQLException e )
        {
            e.printStackTrace();
        }
    }

    private void populateDatabase ( )
    {

    }

    private void exportDatabaseToCsv ( )
    {
    }

}

相关问题