挑戦問題を格納しました

This commit is contained in:
m-mun
2026-09-16 12:25:03 +09:00
parent 093c94fcb8
commit 43ef034dd9
153 changed files with 12477 additions and 0 deletions

View File

@@ -0,0 +1,24 @@
○システム名
DAO
○システム説明
employeeテーブルを管理するDAOプログラムを作成
○出題タイミング
「Java-DB連携(MySQL).pptx」が終了後に出題
○配布物
実行例
○課題の進め方
・個人で実施させる場合(1日予定)
基本的には講師・他の受講生に対する質問はなしにしてください。
※ただし、教室全体のレベルが低い場合は受講生同士での質問はOKにしてください。
時間は日次作業(スピーチ・小テスト等)が終わり次第残りの時間をすべて充てて作業させてください。
・グループで実施させる場合(1.5日予定)
グループでクラス設計をさせ、設計を元に各々作成する(コピペは厳禁)
○納品物
作成したプログラム
○早く終わったら・・・・
テストを実施させてください

View File

@@ -0,0 +1 @@
/~$DAO作成用テーブル定義書.xlsx

View File

@@ -0,0 +1,39 @@
-- employeeテーブルの作成
DROP TABLE IF EXISTS employee;
CREATE TABLE employee (
id_employee INT AUTO_INCREMENT PRIMARY KEY
, nm_employee VARCHAR(50) NOT NULL
, kn_employee VARCHAR(50) NOT NULL
, mail_address VARCHAR(100) NOT NULL
, password VARCHAR(10) NOT NULL
, id_department INT NOT NULL
)
AUTO_INCREMENT = 10000;
-- 部署テーブルの作成
DROP TABLE IF EXISTS department;
CREATE TABLE department (
id_department INT AUTO_INCREMENT PRIMARY KEY
, nm_department VARCHAR(10) NOT NULL
)
AUTO_INCREMENT = 10;
-- 社員テーブルのデータ
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('山田龍也','ヤマダタツヤ','yamada@hoge.jp','aaa',10);
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('高橋準','タカハシジュン','jtaka@hoge.jp','bbb',10);
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('麻枝史明','マエダフミアキ','fmak@hoge.jp','ccc',11);
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('丸戸章介','マルトショウスケ','marusyo@hoge.jp','ddd',12);
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('三宅武','ミヤケタケシ','miya@hoge.jp','eee',13);
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('丸井悠','マルイハルカ','haru@hoge.jp','fff',13);
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('涼元香織','スズモトカオリ','suzumoto@hoge.jp','ggg',13);
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('葉山稔','ハヤマミノル','mhayama@hoge.jp','hhh',14);
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('川上朱里','カワカミアカリ','kawakami@hoge.jp','iii',14);
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('杉井肇','スギイハジメ','sugi@hoge.jp','jjj',15);
-- 部署テーブルのデータ
INSERT INTO department (nm_department) VALUES ('役員');
INSERT INTO department (nm_department) VALUES ('人事・総務部');
INSERT INTO department (nm_department) VALUES ('経理部');
INSERT INTO department (nm_department) VALUES ('システム開発事業部');
INSERT INTO department (nm_department) VALUES ('教育事業部');
INSERT INTO department (nm_department) VALUES ('営業企画部');

View File

@@ -0,0 +1,39 @@
-- employeeテーブルの作成
DROP TABLE IF EXISTS employee;
CREATE TABLE employee (
id_employee serial PRIMARY KEY
,nm_employee varchar(50) NOT NULL
,kn_employee varchar(50) NOT NULL
,mail_address varchar(100) NOT NULL
,password varchar(10) NOT NULL
,id_department integer NOT NULL
);
ALTER SEQUENCE employee_id_employee_seq RESTART WITH 10000;
-- 部署テーブルの作成
DROP TABLE IF EXISTS department;
CREATE TABLE department (
id_department serial PRIMARY KEY
,nm_department varchar(10) NOT NULL
);
alter sequence department_id_department_seq restart with 10;
-- 社員テーブルのデータ
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('山田龍也','ヤマダタツヤ','yamada@hoge.jp','aaa',10);
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('高橋準','タカハシジュン','jtaka@hoge.jp','bbb',10);
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('麻枝史明','マエダフミアキ','fmak@hoge.jp','ccc',11);
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('丸戸章介','マルトショウスケ','marusyo@hoge.jp','ddd',12);
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('三宅武','ミヤケタケシ','miya@hoge.jp','eee',13);
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('丸井悠','マルイハルカ','haru@hoge.jp','fff',13);
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('涼元香織','スズモトカオリ','suzumoto@hoge.jp','ggg',13);
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('葉山稔','ハヤマミノル','mhayama@hoge.jp','hhh',14);
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('川上朱里','カワカミアカリ','kawakami@hoge.jp','iii',14);
INSERT INTO employee (nm_employee, kn_employee, mail_address, password, id_department) VALUES ('杉井肇','スギイハジメ','sugi@hoge.jp','jjj',15);
-- 部署テーブルのデータ
INSERT INTO department (nm_department) VALUES ('役員');
INSERT INTO department (nm_department) VALUES ('人事・総務部');
INSERT INTO department (nm_department) VALUES ('経理部');
INSERT INTO department (nm_department) VALUES ('システム開発事業部');
INSERT INTO department (nm_department) VALUES ('教育事業部');
INSERT INTO department (nm_department) VALUES ('営業企画部');

View File

@@ -0,0 +1,78 @@
/*
* DepartmentDAO.java
* 作成 IT-College 2016
*------------------------------------------------------------
* Copyright(c) Rhizome Inc. All Rights Reserved.
*/
package com.rhizome.example.db.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.rhizome.example.db.dao.base.BaseDao;
import com.rhizome.example.db.entity.Department;
/**
* 部署テーブルのDAOです
* @author IT-College
*
*/
public class DepartmentDAO extends BaseDao<Department> {
/**
* コンストラクタ
* @param con
*/
public DepartmentDAO(Connection con) {
super(con);
}
@Override
protected String getTableId() {
return "department";
}
@Override
protected Department rowMapping(ResultSet rs) throws SQLException {
Department department = new Department();
department.setIdDepartment(rs.getInt("id_department"));
department.setNmDepartment(rs.getString("nm_department"));
return department;
}
@Override
protected List<String> setPrimaryKey() {
List<String> aryPK = new ArrayList<>();
aryPK.add("id_department");
return aryPK;
}
@Override
protected List<String> setColumnsList() {
List<String> aryColumns = new ArrayList<>();
aryColumns.add("id_department");
aryColumns.add("nm_department");
return aryColumns;
}
/**
* id_departmentを除く項目を登録するメソッド
* departmentテーブルでは、pk項目がオートインクリメントのため、pk項目を外して登録します
* @param emp 部署テーブルのDTO
* @return 登録件数
* @throws SQLException SQLの実行失敗時に起こる例外
*/
public int insertRemovePk(Department emp) throws SQLException {
StringBuffer sql = new StringBuffer();
sql.append("INSERT INTO ");
sql.append(super.tableId);
sql.append(" (nm_department) VALUES (?)");
super.stmt = super.con.prepareStatement(sql.toString());
super.stmt.setString(1, emp.getNmDepartment());
return super.stmt.executeUpdate();
}
}

View File

@@ -0,0 +1,136 @@
/*
* EmployeeDAO.java
* 作成 IT-College 2016
*------------------------------------------------------------
* Copyright(c) Rhizome Inc. All Rights Reserved.
*/
package com.rhizome.example.db.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.rhizome.example.db.dao.base.BaseDao;
import com.rhizome.example.db.entity.Employee;
/**
* employeeのDAOクラス
*
* @author IT-College
*
*/
public class EmployeeDAO extends BaseDao<Employee> {
/**
* コンストラクタ
*
* @param con
*/
public EmployeeDAO(Connection con) {
super(con);
}
@Override
protected String getTableId() {
return "employee";
}
@Override
protected Employee rowMapping(ResultSet rs) throws SQLException {
Employee employee = new Employee();
employee.setIdEmployee(rs.getInt("id_employee"));
employee.setNmEmployee(rs.getString("nm_employee"));
employee.setKnEmployee(rs.getString("kn_employee"));
employee.setMailAddress(rs.getString("mail_address"));
employee.setPassword(rs.getString("password"));
employee.setIdDepartment(rs.getInt("id_department"));
return employee;
}
@Override
protected List<String> setPrimaryKey() {
ArrayList<String> aryPK = new ArrayList<String>();
aryPK.add("id_employee");
return aryPK;
}
@Override
protected List<String> setColumnsList() {
ArrayList<String> aryColumns = new ArrayList<>();
aryColumns.add("id_employee");
aryColumns.add("nm_employee");
aryColumns.add("kn_employee");
aryColumns.add("mail_address");
aryColumns.add("password");
aryColumns.add("id_department");
return aryColumns;
};
/**
* パラメータを指定して検索するメソッド
*
* @param param EmployeeのDTO
* @return 検索結果
* @throws SQLException SQLの実行失敗時に起こる例外
*/
public List<Employee> selectByPram(Employee param) throws SQLException {
List<Object> aryParam = new ArrayList<>();
StringBuffer sql = new StringBuffer();
sql.append(super.sqlSelectAll);
String where = " WHERE ";
if (super.setSQLParam(sql, "id_employee", param.getIdEmployee(), aryParam, where)) {
where = " AND ";
}
if (super.setSQLParam(sql, "nm_employee", param.getNmEmployee(), aryParam, where)) {
where = " AND ";
}
if (super.setSQLParam(sql, "kn_employee", param.getKnEmployee(), aryParam, where)) {
where = " AND ";
}
if (super.setSQLParam(sql, "mail_address", param.getMailAddress(), aryParam, where)) {
where = " AND ";
}
if (super.setSQLParam(sql, "password", param.getPassword(), aryParam, where)) {
where = " AND ";
}
if (super.setSQLParam(sql, "id_department", param.getIdDepartment(), aryParam, where)) {
where = " AND ";
}
List<Employee> aryResult = new ArrayList<Employee>();
this.stmt = con.prepareStatement(sql.toString());
this.setParamValue(aryParam, 1);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
aryResult.add(this.rowMapping(rs));
}
stmt.close();
return aryResult;
}
/**
* id_employeeを除く項目を登録するメソッド
* employeeテーブルでは、pk項目がオートインクリメントのため、pk項目を外して登録します
* @param emp 社員テーブルのDTO
* @return 登録件数
* @throws SQLException SQLの実行失敗時に起こる例外
*/
public int insertRemovePk(Employee emp) throws SQLException {
StringBuffer sql = new StringBuffer();
sql.append("INSERT INTO ");
sql.append(super.tableId);
sql.append(" (nm_employee, kn_employee, mail_address, password, id_department) VALUES (?, ?, ?, ?, ?)");
super.stmt = super.con.prepareStatement(sql.toString());
super.stmt.setString(1, emp.getNmEmployee());
super.stmt.setString(2, emp.getKnEmployee());
super.stmt.setString(3, emp.getMailAddress());
super.stmt.setString(4, emp.getPassword());
super.stmt.setInt(5, emp.getIdDepartment());
return super.stmt.executeUpdate();
}
}

View File

@@ -0,0 +1,327 @@
/*
* BaseDao.java
* 作成 IT-College 2016
*------------------------------------------------------------
* Copyright(c) Rhizome Inc. All Rights Reserved.
*/
package com.rhizome.example.db.dao.base;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.rhizome.example.db.entity.base.BaseEntity;
import com.rhizome.example.exception.AppException;
/**
* DAOの基底クラスです。 各SQLにおいての単純なCRUDを提供します。
* DAOを作る場合は、このクラスを継承して作成してください。
*
* @author IT-College
*
*/
public abstract class BaseDao<T extends BaseEntity> {
protected Connection con;
protected PreparedStatement stmt;
protected String tableId;
protected List<String> aryPrimaryKey;
protected List<String> columnsList;
protected String sqlSelectAll;
protected String sqlInsertAllColumn;
protected String sqlUpdateByPK;
protected String sqlDeleteByPK;
protected BaseDao(Connection con) {
this.con = con;
this.tableId = this.getTableId();
this.aryPrimaryKey = this.setPrimaryKey();
this.columnsList = this.setColumnsList();
this.sqlSelectAll = this.getSelectSQL();
this.sqlUpdateByPK = this.getUpdateSQL();
this.sqlDeleteByPK = this.getDeleteSQL();
this.sqlInsertAllColumn = this.getInsertSQL();
}
/**
* 全件検索SQLの取得
*
* @return 全件検索用のSQL
*/
private String getSelectSQL() {
return "SELECT * FROM " + this.tableId;
}
/**
* 更新用SQLの取得 <br />
* 主キーは更新しないものとする
*
* @return 主キー以外の項目を更新するSQL
*/
private String getUpdateSQL() {
StringBuffer strSQL = new StringBuffer();
strSQL.append("UPDATE ");
strSQL.append(this.tableId);
strSQL.append(" SET ");
for (String col : this.columnsList) {
if (!aryPrimaryKey.contains(col)) {
strSQL.append(col);
strSQL.append(" = ?,");
}
}
strSQL.replace(strSQL.length() - 1, strSQL.length(), "");
return strSQL.toString();
}
/**
* 削除用SQLの取得
*
* @return 全件削除用のSQL
*/
private String getDeleteSQL() {
return "DELETE FROM " + this.tableId;
}
/**
* 全カラムを対象とした登録用SQLの取得
*
* @return 全項目を対象としたinsertのSQL
*/
private String getInsertSQL() {
StringBuffer strSQL = new StringBuffer();
strSQL.append("INSERT INTO ");
strSQL.append(this.tableId);
strSQL.append(" (");
for (String col : this.columnsList) {
strSQL.append(col);
strSQL.append(",");
}
strSQL.replace(strSQL.length() - 1, strSQL.length(), "");
strSQL.append(") VALUES (");
for (int i = 0; i < this.aryPrimaryKey.size(); i++) {
strSQL.append("?,");
}
strSQL.replace(strSQL.length() - 1, strSQL.length(), "");
strSQL.append(")");
return strSQL.toString();
}
/**
* 絞り込み条件、登録/更新値等をSQLにセットする
*
* @param aryParam 条件を格納したList int項目ならばIntegerクラス、varchar項目ならばStringクラスで格納してください
* @param index Statementの置換文字インデックス(開始番号)
* @throws SQLException 置換失敗した場合の例外
*/
protected void setParamValue(List<Object> aryParam, int index) throws SQLException {
if (aryParam.size() > 0) {
for (int i = 0; i < aryParam.size(); i++, index++) {
if (aryParam.get(i) instanceof Integer) {
this.stmt.setInt(index, Integer.parseInt(aryParam.get(i).toString()));
} else if (aryParam.get(i) instanceof String) {
this.stmt.setString(index, aryParam.get(i).toString());
}
}
}
}
/**
* 更新・登録・削除を行うSQLの実行
*
* @return 変更件数
* @throws SQLException
*/
protected int doExecuteUpdate() throws SQLException {
int ret = -1;
ret = this.stmt.executeUpdate();
this.stmt.close();
return ret;
}
/**
* 全検索メソッド
*
* @return 検索結果
* @throws SQLException
*/
public List<T> findAll() throws SQLException {
List<T> aryResult = new ArrayList<T>();
String sql = this.sqlSelectAll;
this.stmt = con.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
aryResult.add(this.rowMapping(rs));
}
stmt.close();
return aryResult;
}
/**
* 主キー検索メソッド
* @param aryParam 主キー条件を格納したList(int項目ならばIntegerクラス、varchar項目ならばStringクラスで格納してください)
* @return 検索した結果のDTO
* @throws SQLException SQLで何かしらのエラーが発生した場合の例外
* @throws AppException SQL生成時に起こった例外
*/
public T findByPrimaryKey(List<Object> aryParam) throws SQLException, AppException {
this.stmt = con.prepareStatement(sqlConcatPrimaryKey(this.sqlSelectAll, aryParam));
this.setParamValue(aryParam, 1);
ResultSet rs = stmt.executeQuery();
T ret = null;
if (rs.next()) {
ret = this.rowMapping(rs);
}
stmt.close();
return ret;
}
/**
* * 登録を行うメソッド
*
* @param aryParam 登録値の順に指定(必須)
* @return 登録件数
* @throws SQLException SQLで何かしらのエラーが発生した場合の例外
*/
public int insertByAllColumns(List<Object> aryParam) throws SQLException {
this.stmt = con.prepareStatement(this.sqlInsertAllColumn);
this.setParamValue(aryParam, 1);
return this.doExecuteUpdate();
}
/**
* 主キーを更新条件に値を登録するメソッド
*
* @param aryParam 更新値 テーブルに設定しているカラム順に指定してください。全項目必須です。
* @return 更新件数
* @throws SQLException SQLで何かしらのエラーが発生した場合の例外
* @throws AppException SQL生成時に起こった例外
*/
public int updateByPrimaryKey(List<Object> aryParam, List<Object> aryPKeyParam) throws SQLException, AppException {
this.stmt = con.prepareStatement(sqlConcatPrimaryKey(this.sqlUpdateByPK, aryPKeyParam));
this.setParamValue(aryParam, 1);
this.setParamValue(aryPKeyParam, aryParam.size() + 1);
return this.doExecuteUpdate();
}
/**
* 主キーを削除条件にレコードを削除するメソッド
*
* @param aryParam 主キー条件を格納したList(int項目ならばIntegerクラス、varchar項目ならばStringクラスで格納してください)
* @return 削除件数
* @throws SQLException SQLで何かしらのエラーが発生した場合の例外
* @throws AppException SQL生成時に起こった例外
*/
public int deleteByPrimaryKey(List<Object> aryPKeyParam) throws SQLException, AppException {
this.stmt = con.prepareStatement(sqlConcatPrimaryKey(this.sqlDeleteByPK, aryPKeyParam));
this.setParamValue(aryPKeyParam, 1);
return this.doExecuteUpdate();
}
/**
* SQLに主キー条件をWhereとして追加するメソッド
* @param sql 主キー条件を追加したいSQL
* @param aryPKeyParam 主キー条件に指定したい値のリスト(主キーのカラム数と差異がある場合は例外が発生します)
* @return 主キー条件を追加した状態のSQL
* @throws AppException SQL生成時に起こった例外
*/
private String sqlConcatPrimaryKey(String sql, List<Object> aryPKeyParam) throws AppException {
StringBuffer sbSQL = new StringBuffer();
if (aryPrimaryKey.size() != aryPKeyParam.size()) {
throw new AppException(AppException.ERROR_CODE.PARAM_SIZE_ERROR);
}
sbSQL.append(sql);
for (int i = 0; i < aryPrimaryKey.size(); i++) {
if (i == 0) {
sbSQL.append(" WHERE ");
} else {
sbSQL.append(" AND ");
}
sbSQL.append(aryPrimaryKey.get(i));
sbSQL.append(" = ?");
}
return sbSQL.toString();
}
// ============================================ Utilメソッド
/**
* 指定された文字列に"%"が含まれている場合はLIKE、なければ"="を返すメソッド
* @param val 条件式に設定したい値
* @return LIKE or =
*/
protected String likeORequals(String val) {
if (val.contains("%")) {
return " LIKE ";
}
return " = ";
}
/**
* 条件式に設定する値を追記するメソッド
*
* @param sql 追記対象のSQL
* @param columns 対象のカラム名
* @param param 条件に指定したい値(int項目ならばIntegerクラス、varchar項目ならばStringクラスで格納してください)
* @param aryParam 条件値を格納しているLIST(SQL生成時に、paramの値を格納します)
* @param where 条件式を連結する際の文字列(WHERE, AND, ORなど)
* @return 追記が正常に出来れていればTRUE, できなかった場合はfalse
*/
protected boolean setSQLParam(StringBuffer sql, String columns, Object param, List<Object> aryParam, String where) {
if (param != null) {
if (param instanceof String) {
if (((String) param).length() > 0) {
sql.append(where);
sql.append(columns);
sql.append(this.likeORequals((String) param));
sql.append("?");
aryParam.add(param);
return true;
}
} else {
sql.append(where);
sql.append(columns);
sql.append(" = ?");
aryParam.add(param);
return true;
}
}
return false;
}
// ============================================ 抽象メソッド
/**
* テーブル物理名を取得する
*
* @return tableName
*/
protected abstract String getTableId();
/**
* 取得したデータのマッピング
*
* @param rs
* @return ArrayList<BaseEntity>
*/
protected abstract T rowMapping(ResultSet rs) throws SQLException;
/**
* カラム一覧をセットする
*
* @return
*/
protected abstract List<String> setColumnsList();
/**
* PKをセットする
*
* @return
*/
protected abstract List<String> setPrimaryKey();
}

View File

@@ -0,0 +1,71 @@
/*
* Department.java
* 作成 IT-College 2016
*------------------------------------------------------------
* Copyright(c) Rhizome Inc. All Rights Reserved.
*/
package com.rhizome.example.db.entity;
import com.rhizome.example.db.entity.base.BaseEntity;
/**
* DepartmentテーブルのEntity
* @author IT-College
*
*/
public class Department implements BaseEntity {
public static final String TITLE_ID_DEPARTMENT = "部署ID";
public static final String TITLE_NM_DEPARTMENT = "部署名";
/** 部署ID */
private Integer idDepartment;
/** 部署名 */
private String nmDepartment;
/**
* 部署IDを取得します
* @return 部署ID
*/
public Integer getIdDepartment() {
return idDepartment;
}
/**
* 部署IDを設定します
* @param idDepartment 部署ID
*/
public void setIdDepartment(Integer idDepartment) {
this.idDepartment = idDepartment;
}
/**
* 部署名を取得します
* @return 部署名
*/
public String getNmDepartment() {
return nmDepartment;
}
/**
* 部署名を設定します
* @param nmDepartment 部署名
*/
public void setNmDepartment(String nmDepartment) {
this.nmDepartment = nmDepartment;
}
@Override
public String getHeaderTitle() {
StringBuffer sb = new StringBuffer();
sb.append(TITLE_ID_DEPARTMENT);
sb.append(TAB);
sb.append(TITLE_NM_DEPARTMENT);
return sb.toString();
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(idDepartment);
sb.append(TAB);
sb.append(nmDepartment);
return sb.toString();
}
}

View File

@@ -0,0 +1,155 @@
/*
* Employee.java
* 作成 IT-College 2016
*------------------------------------------------------------
* Copyright(c) Rhizome Inc. All Rights Reserved.
*/
package com.rhizome.example.db.entity;
import com.rhizome.example.db.entity.base.BaseEntity;
/**
* EmployeeテーブルのEntity
* @author IT-College
*
*/
public class Employee implements BaseEntity {
public static final String TITLE_ID_EMPLOYEE = "社員ID";
public static final String TITLE_NM_EMPLOYEE = "社員名";
public static final String TITLE_KN_EMPLOYEE = "フリガナ";
public static final String TITLE_MAIL = "メールアドレス";
public static final String TITLE_PASSWORD = "パスワード";
public static final String TITLE_ID_DEPARTMENT = "部署ID";
/** 社員ID */
private Integer idEmployee;
/** 社員名 */
private String nmEmployee;
/** 社員名カナ */
private String knEmployee;
/** メールアドレス */
private String mailAddress;
/** パスワード */
private String password;
/** 部署ID */
private Integer idDepartment;
/**
* 社員IDを取得します
* @return 社員ID
*/
public Integer getIdEmployee() {
return idEmployee;
}
/**
* 社員IDを設定します
* @param idEmployee 社員ID
*/
public void setIdEmployee(Integer idEmployee) {
this.idEmployee = idEmployee;
}
/**
* 社員名を取得します
* @return 社員名
*/
public String getNmEmployee() {
return nmEmployee;
}
/**
* 社員名を設定します
* @param nmEmployee 社員名
*/
public void setNmEmployee(String nmEmployee) {
this.nmEmployee = nmEmployee;
}
/**
* 社員名カナを取得します
* @return 社員名カナ
*/
public String getKnEmployee() {
return knEmployee;
}
/**
* 社員名カナを設定します
* @param knEmployee 社員名カナ
*/
public void setKnEmployee(String knEmployee) {
this.knEmployee = knEmployee;
}
/**
* メールアドレスを取得します
* @return メールアドレス
*/
public String getMailAddress() {
return mailAddress;
}
/**
* メールアドレスを設定します
* @param mailAddress メールアドレス
*/
public void setMailAddress(String mailAddress) {
this.mailAddress = mailAddress;
}
/**
* パスワードを取得します
* @return パスワード
*/
public String getPassword() {
return password;
}
/**
* パスワードを設定します
* @param password パスワード
*/
public void setPassword(String password) {
this.password = password;
}
/**
* 部署IDを取得します
* @return 部署ID
*/
public Integer getIdDepartment() {
return idDepartment;
}
/**
* 部署IDを設定します
* @param idDepartment 部署ID
*/
public void setIdDepartment(Integer idDepartment) {
this.idDepartment = idDepartment;
}
@Override
public String getHeaderTitle() {
StringBuffer sb = new StringBuffer();
sb.append(TITLE_ID_EMPLOYEE);
sb.append(TAB);
sb.append(TITLE_NM_EMPLOYEE);
sb.append(TAB);
sb.append(TITLE_KN_EMPLOYEE);
sb.append(TAB);
sb.append(TITLE_MAIL);
sb.append(TAB);
sb.append(TITLE_PASSWORD);
sb.append(TAB);
sb.append(TITLE_ID_DEPARTMENT);
return sb.toString();
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(idEmployee);
sb.append(TAB);
sb.append(nmEmployee);
sb.append(TAB);
sb.append(knEmployee);
sb.append(TAB);
sb.append(mailAddress);
sb.append(TAB);
sb.append(password);
sb.append(TAB);
sb.append(idDepartment);
return sb.toString();
}
}

View File

@@ -0,0 +1,22 @@
/*
* BaseEntity.java
* 作成 IT-College 2016
*------------------------------------------------------------
* Copyright(c) Rhizome Inc. All Rights Reserved.
*/
package com.rhizome.example.db.entity.base;
/**
* 各Entityのインタフェース
* @author IT-College
*
*/
public interface BaseEntity {
String TAB = "\t";
/**
* カラム名一覧を取得するメソッド
* @return カラム名一覧の文字列
*/
String getHeaderTitle();
}

View File

@@ -0,0 +1,70 @@
/*
* AppException.java
* 作成 IT-College 2016
*------------------------------------------------------------
* Copyright(c) Rhizome Inc. All Rights Reserved.
*/
package com.rhizome.example.exception;
import java.sql.SQLException;
/**
* このシステムの例外をまとめたものです。
* エラーコードからどのようなエラーが起きているかを判断してください。
* @author IT-College
*
*/
public class AppException extends Exception {
public enum ERROR_CODE {
JDBC_ERROR
,DB_ERROR
,SQL_ERROR
,PARAM_SIZE_ERROR
,IO_ERROR
,NOT_FOUND
,INSERT_FAILD
,UPDATE_FAILD
,DELETE_FAILD
,OTHER_ERROR
}
private ERROR_CODE st = ERROR_CODE.OTHER_ERROR;
public AppException(ERROR_CODE st) {
this.st = st;
}
public AppException(SQLException e) {
// TODO:ベンダー固有エラーコードから内容を判定
this(ERROR_CODE.OTHER_ERROR);
}
@Override
public void printStackTrace() {
System.out.println(this.errorMessage());
super.printStackTrace();
}
public String errorMessage() {
switch (this.st) {
case JDBC_ERROR:
return "JDBCドライバ周辺に不備があります";
case DB_ERROR:
return "データベースに障害が発生しています";
case SQL_ERROR:
return "SQLにエラーがあります";
case PARAM_SIZE_ERROR:
return "SQLのパラメータ定義に誤りがあります";
case IO_ERROR:
return "入出力装置にエラーが発生しています";
case NOT_FOUND:
return "入力された値で情報がみつかりませんでした";
case INSERT_FAILD:
return "登録できませんでした";
case UPDATE_FAILD:
return "更新できませんでした";
case DELETE_FAILD:
return "削除できませんでした";
default:
return "予期せぬエラーです!";
}
}
}

View File

@@ -0,0 +1,34 @@
/*
* Main.java
* 作成 IT-College 2016
*------------------------------------------------------------
* Copyright(c) Rhizome Inc. All Rights Reserved.
*/
package com.rhizome.example.main;
/**
* rezodbに定義されているテーブルのメンテナンスを行うクラスです。
* @author IT-College
*
*/
public class Main {
/** 対象テーブル判定用 **/
private static int mode = 0;
/**
* 対象テーブルの名前を取得するメソッド
* @return 現在の対象テーブル名
*/
private String targetTableName() {
return Main.mode == 0 ? "社員テーブル" : "部署テーブル";
}
/**
* システムのエントリーポイントです。
* コマンドライン引数は使用していません。
* @param args 使用していません
*/
public static void main(String[] args) {
}
}

View File

@@ -0,0 +1,50 @@
/*
* AccessDepartment.java
* 作成 IT-College 2016
*------------------------------------------------------------
* Copyright(c) Rhizome Inc. All Rights Reserved.
*/
package com.rhizome.example.service;
import java.sql.Connection;
import java.sql.SQLException;
import com.rhizome.example.db.dao.DepartmentDAO;
import com.rhizome.example.db.entity.Department;
import com.rhizome.example.exception.AppException;
import com.rhizome.example.service.base.BaseAccess;
import com.rhizome.example.util.DbUtil;
/**
* Departmentのトランザクション処理クラス
* @author IT-College
*
*/
public class AccessDepartment extends BaseAccess<Department> {
private DepartmentDAO departmentDAO;
public AccessDepartment() throws AppException {
super();
}
@Override
protected DepartmentDAO getDaoInstance(Connection con) {
departmentDAO = new DepartmentDAO(super.con);
return departmentDAO;
}
public int insertDepartment(Department dep) throws SQLException, AppException {
int ret = -1;
try {
ret = departmentDAO.insertRemovePk(dep);
super.con.commit();
} catch(SQLException e) {
super.con.rollback();
throw new AppException(e);
} finally {
DbUtil.closeConnection(con);
}
return ret;
}
}

View File

@@ -0,0 +1,55 @@
/*
* AccessEmployee.java
* 作成 IT-College 2016
*------------------------------------------------------------
* Copyright(c) Rhizome Inc. All Rights Reserved.
*/
package com.rhizome.example.service;
import java.sql.Connection;
import java.sql.SQLException;
import com.rhizome.example.db.dao.EmployeeDAO;
import com.rhizome.example.db.entity.Employee;
import com.rhizome.example.exception.AppException;
import com.rhizome.example.service.base.BaseAccess;
import com.rhizome.example.util.DbUtil;
/**
* Employeeのトランザクション処理クラス
* @author IT-College
*
*/
public class AccessEmployee extends BaseAccess<Employee> {
private EmployeeDAO employeeDAO;
public AccessEmployee() throws AppException {
super();
}
@Override
protected EmployeeDAO getDaoInstance(Connection con) {
if(employeeDAO == null) { employeeDAO = new EmployeeDAO(super.con); }
return employeeDAO;
}
/**
* 社員情報を登録するメソッド
* @param emp 社員情報DTO
* @return 登録件数
* @throws SQLException
* @throws AppException
*/
public int insertEmploee(Employee emp) throws SQLException, AppException {
int ret = -1;
try {
ret = employeeDAO.insertRemovePk(emp);
super.con.commit();
} catch(SQLException e) {
super.con.rollback();
throw new AppException(e);
} finally {
DbUtil.closeConnection(con);
}
return ret;
}
}

View File

@@ -0,0 +1,164 @@
/*
* BaseAccess.java
* 作成 IT-College 2016
*------------------------------------------------------------
* Copyright(c) Rhizome Inc. All Rights Reserved.
*/
package com.rhizome.example.service.base;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import com.rhizome.example.db.dao.base.BaseDao;
import com.rhizome.example.db.entity.base.BaseEntity;
import com.rhizome.example.exception.AppException;
import com.rhizome.example.util.DbUtil;
public abstract class BaseAccess<E extends BaseEntity> {
protected BaseDao<E> dao;
protected Connection con;
protected BaseAccess() throws AppException {
try {
con = DbUtil.getConnection();
dao = this.getDaoInstance(con);
} catch (ClassNotFoundException e) {
throw new AppException(AppException.ERROR_CODE.JDBC_ERROR);
} catch (SQLException e) {
throw new AppException(e);
}
}
/**
* 全件検索トランザクション処理を行う
*
* @return 検索結果
* @throws AppException DAOから発生した例外
* @throws SQLException DAOから発生した例外
*/
public List<E> doSelectAll() throws AppException, SQLException {
List<E> entityList = null;
entityList = dao.findAll();
try {
DbUtil.closeConnection(con);
} catch (SQLException e) {
throw new AppException(e);
}
return entityList;
}
/**
* 検索トランザクション処理を行う
*
* @param pkObj 検索条件
* @return 検索結果
* @throws AppException DAOから発生した例外
* @throws SQLException DAOから発生した例外
*/
public E doSelectByPKey(Object... pkObj) throws AppException, SQLException {
List<Object> pkList = Arrays.asList(pkObj);
E entity = this.doSelectPrimaryKey(pkList);
try {
DbUtil.closeConnection(con);
} catch (SQLException e) {
throw new AppException(e);
}
return entity;
}
/**
* 登録トランザクション処理を行う
*
* @param aryParam 登録する値
* @return 登録件数
* @throws AppException DAOから発生した例外
*/
public int doInsert(List<Object> aryParam) throws AppException {
int numRet = 0;
try {
try {
numRet = dao.insertByAllColumns(aryParam);
con.commit();
} catch (SQLException e) {
con.rollback();
} finally {
DbUtil.closeConnection(con);
}
} catch (SQLException e) {
throw new AppException(e);
}
return numRet;
}
/**
* 更新トランザクション
*
* @param aryParam 更新内容
* @param pkObj 主キー条件に設定する値
* @return 削除件数
* @throws AppException DAOから発生した例外
*/
public int doUpdate(List<Object> aryParam, Object... pkObj) throws AppException {
int numRet = 0;
List<Object> pkList = Arrays.asList(pkObj);
try {
try {
numRet = dao.updateByPrimaryKey(aryParam, pkList);
con.commit();
} catch (SQLException e) {
con.rollback();
throw new AppException(e);
} finally {
DbUtil.closeConnection(con);
}
} catch (SQLException e) {
throw new AppException(e);
}
return numRet;
}
/**
* 削除トランザクション
*
* @param pkObj 削除条件
* @return 削除件数
* @throws AppException DAOから発生した例外
*/
public int doDelete(Object... pkObj) throws AppException {
int numRet = 0;
List<Object> pkList = Arrays.asList(pkObj);
try {
try {
con = DbUtil.getConnection();
numRet = dao.deleteByPrimaryKey(pkList);
con.commit();
} catch (ClassNotFoundException e) {
throw new AppException(AppException.ERROR_CODE.JDBC_ERROR);
} catch (SQLException e) {
con.rollback();
throw new AppException(e);
} finally {
DbUtil.closeConnection(con);
}
} catch (SQLException e) {
throw new AppException(e);
}
return numRet;
}
/**
* 主キー検索処理
*
* @param pkList 主キー条件
* @return 検索結果
* @throws AppException DAOから発生した例外
* @throws SQLException DAOから発生した例外
*/
private E doSelectPrimaryKey(List<Object> pkList) throws AppException, SQLException {
return dao.findByPrimaryKey(pkList);
}
protected abstract BaseDao<E> getDaoInstance(Connection con);
}

View File

@@ -0,0 +1,55 @@
/*
* CommonUtil.java
* 作成 IT-College 2016
*------------------------------------------------------------
* Copyright(c) Rhizome Inc. All Rights Reserved.
*/
package com.rhizome.example.util;
import java.util.Scanner;
/**
* 文字列変換や数値チェックなどの細かい調整処理を行うメソッドを集めたクラスです
* @author IT-College
*
*/
public class CommonUtil {
private static Scanner scanner = new Scanner(System.in);
/** インスタンス禁止 */
private CommonUtil() { }
/**
* コマンドライン上で入力された値を取得するメソッド
* @return 入力された文字列
*/
public static String getInputLine() {
String line = scanner.nextLine();
return line;
}
/**
* Nullを空文字("")に変換するメソッド
* @param value 判定する文字列
* @return 変換結果
*/
public static String convertNullToBlank(String value) {
if (value == null) {
return "";
}
return value;
}
/**
* 空文字をNullに変換するメソッド
* @param value 判定する文字列
* @return 変換結果
*/
public static String convertBlankToNull(String value) {
if (value == null || "".equals(value.trim())) {
return null;
}
return value;
}
}

View File

@@ -0,0 +1,67 @@
/*
* DbUtil.java
* 作成 IT-College 2016
*------------------------------------------------------------
* Copyright(c) Rhizome Inc. All Rights Reserved.
*/
package com.rhizome.example.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* データベースの接続・切断を行うクラスです。
* @author IT-College
*
*/
public class DbUtil {
// 定数定義(共通)
private static final String DB_HOST = "127.0.0.1";
private static final String DB_NAME = "rezodb";
private static final String DB_USER = "rezouser";
private static final String DB_PASS = "Rezo_0000";
// 定数定義(PostgreSQL用)
// private static final String DBMS = "postgresql";
// private static final String DB_DRIVER = "org." + DBMS + ".Driver";
// private static final String DB_PORT = "5432";
// private static final String DB_URL = "jdbc:" + DBMS + "://" + DB_HOST + ":" + DB_PORT + "/" + DB_NAME;
// 定数定義(MySQL用)
private static final String DBMS ="mysql";
private static final String DB_DRIVER = "com." + DBMS + ".cj.jdbc.Driver";
private static final String DB_PORT = "3306";
private static final String DB_URL = "jdbc:" + DBMS + "://" + DB_HOST + ":" + DB_PORT + "/" + DB_NAME;
// + "?serverTimezone=JST"; //JDBCドライバのバージョン8.0.22以前を利用する場合は必要
// インスタンス化の禁止
private DbUtil() {}
// Connectionを単一のインスタンスとする
private static Connection con;
/**
* DBのコネクションを取得
* @return DBコネクション
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection getConnection() throws ClassNotFoundException, SQLException {
if (con == null || con.isClosed()) {
Class.forName(DB_DRIVER);
con = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
con.setAutoCommit(false);
}
return con;
}
/**
* DBとのコネクションを切断
* @param con DBコネクション
* @throws SQLException
*/
public static void closeConnection(Connection con) throws SQLException {
if (con != null) { con.close(); }
}
}

View File

@@ -0,0 +1,2 @@
java -jar DAO.jar
pause