CodeGym/Java Course/All lectures for JA purposes/オブジェクトをデータベースに保存する

オブジェクトをデータベースに保存する

使用可能

JDBC データ型の完全なリスト

JDBC では、既知のデータ型に加えて、DBMS の多くのネイティブ データ型を操作できます。以下に型とそれを取得するための関数をリストします。

タイプ 方法
配列 getArray()
アスキーストリーム getAsciiStream()
BigDecimal getBigDecimal()
バイナリストリーム getBinaryStream()
getBlob()
ブール値 getBoolean()
getBlob()
ブール値 getBoolean()
バイト getByte()
バイト getBytes()
キャラクターストリーム getCharacterStream()
クロブ getClob()
日にち getDate()
ダブル getDouble()
浮く getFloat()
整数 getInt()
長さ getLong()
NCharacterStream getNCharacterStream()
物体 getObject()
参照 getRef()
行ID getRowId()
短い getShort()
SQLXML getSQLXML()
getString()
時間 時間をもらう()
タイムスタンプ getタイムスタンプ()
ユニコードストリーム getUnicodeStream()
URL getURL()

すでにプリミティブ型について検討しました。次に、オブジェクトを操作してみましょう。

BLOBデータ型

オブジェクトをデータベースに保存したい場合、SQL BLOB タイプを使用するのが最も簡単な方法です。JDBC には Blob と呼ばれる対応物があります。

BLOB はバイナリラージオブジェクト略ですバイト配列を格納するために使用されます。JDBC の BLOB 型はインターフェイスであり、次の 2 つの方法でデータをそこに配置 (および受信) できます。

  • 入力ストリームの使用
  • バイト配列の使用

例: 列番号 3 には BLOB タイプが含まれます。

Statement statement = connection.createStatement();
    ResultSet results = statement.executeQuery("SELECT * FROM user");
    results.first();

    Blob blob = results.getBlob(3);
    InputStream is = blob.getBinaryStream();

独自の Blob オブジェクトを作成するには、createBlob()関数を使用する必要があります。例:

String insertQuery = “INSERT INTO images(name, image) VALUES (?, ?);
PreparedStatement statement = connection.prepareStatement(insertQuery);

// Create a Blob object and get an OtputStream from it to write data to it
Blob blob = connection.createBlob();

// Populate the Blob with data...
OutputStream os = blob.setBinaryStream(1);

// Passing Blob as query parameter
statement.setBlob(2, blob);
statement.execute();

BLOB にデータを設定するには 2 つの方法があります。1 つ目はOutputSteam経由です。

Path avatar = Paths.get("E:\\images\\cat.jpg");
OutputStream os = blob.setBinaryStream(1);
Files.copy(avatar, os);

そして 2 番目 - バイトで埋めることによって:

Path avatar = Paths.get("E:\\images\\cat.jpg");
byte[] content = Files.readAllBytes(avatar);
blob.setBytes(1, content);

Java オブジェクトをデータベースに保存する

バイト配列、バイト ストリームなどのバイナリ オブジェクトをデータベースに保存する方法を学習しました。Java オブジェクトについてはどうでしょうか? Java オブジェクトをデータベースに保存するにはどうすればよいでしょうか?

会社の従業員を記述するEmployee Java クラスがあるとします。

public class Employee {
    public Integer id;
    public String name;
    public String occupation;
    public Integer salary;
    public Date joinDate;
}

JDBC を使用してこのクラスのオブジェクトをデータベースに保存するにはどうすればよいでしょうか?

実際、あなたは知るべきことをすべてすでに知っています。まず、このクラスに対応するテーブルをデータベースに作成する必要があります。たとえば、これは次のとおりです。

CREATE TABLE employee {
    id INT PRIMARY KEY NOT NULL,
    name VARCHAR(100),
    occupation VARCHAR(100),
    salary INT,
    join_date DATE
}

次に、 Employeeクラスのオブジェクトをベースに追加するコードを作成しましょう。

public static boolean addEmployee(Connection connection, Employee employee) throws Exception {
    	// Create and prepare a query to insert data into the table
    	String insertQuery = "INSERT INTO employee(name, occupation, salary, join_date ) VALUES (?, ?, ?, ?)";
    	PreparedStatement statement = connection.prepareStatement(insertQuery);

    	// Populate the query with data from the Employee object
    	statement.setString(1, employee.name);
    	statement.setString(2, employee.occupation);
    	statement.setInt(3, employee.salary);
    	statement.setDate(4, employee.joinDate);

    	// Execute our query and it returns true if a new row has been added
    	int count = statement.executeUpdate();
    	return count > 0;
    }

シンプルかつ明確。この方法はうまくいきます。

データベースからの Java オブジェクトの読み取り

オブジェクトをデータベースに書き込む方法を学習しました。次に、データベースからオブジェクトを読み取るコードを作成しましょう。ID によってデータベースからオブジェクトを読み取るコードから始めましょう。

public static Employee getEployeeById(Connection connection, int id) throws Exception {
    	// Create and prepare a query to get an employee from the table
    	PreparedStatement statement = connection.prepareStatement("SELECT * FROM employee WHERE id = ?");
    	statement.setInt(1, id);

    	// Execute our query and it returns null if there are no rows in the query result
    	ResultSet results = statement.executeQuery();
    	if (!results.first())
        	return null;

    	// Populate the Employee object with the data from the ResultSet
    	Employee employee = new Employee();
    	employee.id = results.getInt(1);
    	employee.name = results.getString(2);
    	employee.occupation = results.getString(3);
    	employee.salary = results.getInt(4);
    	employee.joinDate = results.getDate(5);
    	return employee;
}

そして、1 つのオブジェクトではなく複数のオブジェクトが必要な場合はどうすればよいでしょうか? こんな要望も書きやすいです。私たちの会社の従業員全員を集めてみましょう:

public static List<Employee> getAllEployees(Connection connection) throws Exception {
	// Create and execute a query to get employees from the table
	Statement statement = connection.createStatement();
	ResultSet results = statement.executeQuery("SELECT * FROM employee");

	ArrayList<Employee> list = new ArrayList<Employee>();
	while (results.next()) {
        // Populate the Employee object with the data from the current row of the ResultSet
	        Employee employee = new Employee();
	        employee.id = results.getInt(1);
	        employee.name = results.getString(2);
	        employee.occupation = results.getString(3);
	        employee.salary = results.getInt(4);
	        employee.joinDate = results.getDate(5);

	        list.add(employee);
	}
	return list;
}

ちなみに、このようなメソッドが多数ある場合は、それぞれのメソッドで ResultSet文字列をオブジェクトに変換するための同じコードを記述する必要があります。職員。したがって、このコードは別のメソッドに移動できます。

これは、 Employeeクラスに Enum、InputStream、またはデータベースに保存したい他のオブジェクトへの参照などの複雑なフィールドが含まれている場合に特に便利です。

コメント
  • 人気
  • 新規
  • 古い
コメントを残すには、サインインしている必要があります
このページにはまだコメントがありません