多対1の関係にあるときに、Javaでデータベースにオブジェクトを保存する方法に関して問題があります。
基本的に、UserVOとGroupVOの2つのクラスがあり、次のようになります。
public class UserVO extends ValueObject implements Serializable {
/**
* The default serial version ID
*/
private static final long serialVersionUID = 1L;
private String login;
private String password;
private Long groupId;
public UserVO() {
super();
this.setLogin("");
this.setPassword("");
this.setGroupId(0L);
}
// all the getters and setters
// ...
}
と
public final class GroupVO extends ValueObject implements Serializable {
/**
* The default serial version ID
*/
private static final long serialVersionUID = 1L;
private String description;
private Set<UserVO> users = new HashSet<UserVO>();
public GroupVO() {
super();
this.setDescription("");
}
// all the getters and setters
// ...
}
それらのスーパークラスは非常に単純な抽象クラスです。
public abstract class ValueObject {
private Long id;
private String name;
public ValueObject() {
super();
// the ID is auto-generated
// this.setId(0L);
this.setName("");
}
// all the getters and setters
// ...
}
次に、それらのDAOクラスを作成する必要があります。UserDAOでは、DBにユーザーを作成して挿入するために次のようにしています。
@Override
public Long create(UserVO user) throws IllegalArgumentException, DAOException {
if (user.getId() != null) {
throw new IllegalArgumentException("User may already be created, the user ID is not null.");
}
Object[] values = { user.getName(), user.getLogin(), user.getPassword(), user.getGroupId() };
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet generatedKeys = null;
try {
connection = daoFactory.getConnection();
preparedStatement = DAOUtil.prepareStatement(connection, SQL_CREATE_USER, true, values);
int affectedRows = preparedStatement.executeUpdate();
if (affectedRows == 0) {
throw new DAOException("Creating user failed, no rows affected.");
}
generatedKeys = preparedStatement.getGeneratedKeys();
if (generatedKeys.next()) {
user.setId(generatedKeys.getLong(1));
} else {
throw new DAOException("Creating user failed, no generated key obtained.");
}
} catch (SQLException e) {
throw new DAOException(e);
} finally {
DAOUtil.close(connection, preparedStatement, generatedKeys);
}
return user.getId();
}
いくつかのヘルパークラスもありますが、私のコードを理解していると思います:)。
そして、これはGroupDAOの作成メソッドです。
@Override
public Long create(GroupVO group) throws IllegalArgumentException, DAOException {
if (group.getId() != null) {
throw new IllegalArgumentException("Group may already be created, the group ID is not null.");
}
Object[] values = { group.getName(), group.getDescription() };
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet generatedKeys = null;
try {
connection = daoFactory.getConnection();
preparedStatement = DAOUtil.prepareStatement(connection, SQL_CREATE_GROUP, true, values);
int affectedRows = preparedStatement.executeUpdate();
if (affectedRows == 0) {
throw new DAOException("Creating group failed, no rows affected.");
}
generatedKeys = preparedStatement.getGeneratedKeys();
if (generatedKeys.next()) {
group.setId(generatedKeys.getLong(1));
} else {
throw new DAOException("Creating group failed, no generated key obtained.");
}
} catch (SQLException e) {
throw new DAOException(e);
} finally {
DAOUtil.close(connection, preparedStatement, generatedKeys);
}
return group.getId();
}
ここで、グループを作成してDBに保存するために、main関数で小さなテストを行うと、すべてがうまくいきます。
DAOFactory usersGroupsRolesFactory = DAOFactory.getInstance("UsersGroupsRolesDB.jdbc");
System.out.println("DAOFactory successfully obtained: " + usersGroupsRolesFactory);
// Create an instance of the GroupDAO class
GroupDAO dao = usersGroupsRolesFactory.getGroupDAO();
// Create some GroupVO objects
GroupVO group1 = new GroupVO();
group1.setName("Administrators");
group1.setDescription("These users have all the right in the application");
dao.create(group1);
GroupVOクラスには一連のUserVOオブジェクトがあり、次のように入力すると、main関数に次のように入力します。
UserVO user1 = new UserVO();
user1.setName("Palancica Pavel");
user1.setLogin("login_pavel");
user1.setPassword("password_pavel");
group1.getUsers().add(user1); // I may also add some more users
そして、私が初めて電話をかけたと言います:dao.create(group1);
通常、これはグループ情報だけでなく、関連するすべてのUserVOオブジェクトも保存する必要があります。
つまり、GroupDAOの「作成」機能では、グループIDが正常に生成された後、他の多くのコードを実行する必要があります。
これは、これらのユーザーをDBに保存する正しい方法だと思います。これは、GroupDAOクラスを作成してUserDAOクラスと通信し、DAOFactoryと通信する必要があると思うためです。DAOFactoryは、私の場合、UserDAOを提供します。またはGroupDAOオブジェクト。または、UserDAOクラスを使用せずに、これらのユーザーを保存するためのすべてのDBインタラクションを実行できます。
私が考えているそのコードは非常に長く、乱雑/スパゲッティのようであり、これが正しいアプローチであるかどうかはよくわかりません:(。
ORMフレームワークを使用していることに注意してください。
みんな教えてください、どう思いますか?詳細が必要な場合は、プロジェクトをお送りします。商用ではありません:D
前もって感謝します