preparedstatement with sql query referencing multiple tables - java

So I am trying to find an example online about creating a preparedStatement that has an sql query referencing multiple tables.
For e.g. The examples I've encountered so far are always
e.g.
s = conn.prepareStatement ("DELETE FROM Users WHERE id_user = ?");
s.setInt (1, 2);
where there is only one table involved, and the method exists in the same class of the database table. E.g. User.class , user table in database.
The query that I have requires me to set the place holder from another table/class. In this case, my method exists in the User.class, however, it requires a the binding from a Group object.
SELECT DISTINCT *
FROM usuarios
WHERE NOT EXISTS
(SELECT * FROM usuarios_grupos
WHERE usuarios_grupos.id_grupo = ?
AND usuarios_grupos.id_usuario = usuarios.id_usuario);
Will the method be the following:
public List<Usuarious> list(Grupos groups) throws DAOExceptions {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<Usuarious> users = new ArrayList<Usuarious>();
try {
connection = daoFactory.getConnection();
preparedStatement = connection.prepareStatement(SQL_LIST_ALL);
preparedStatement.setInt(1, groups.getId_grupo());
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
users.add(mapUser(resultSet));
}
} catch (SQLException e) {
throw new DAOExceptions(e);
} finally {
close(connection, preparedStatement, resultSet);
}
return users;
}
or will it be written differently?? because I seem to be getting a NPE with this, and from the examples I've seen online. The query always reference 1 table. Is what I'm doing here wrong?
okay here is my method for groups.getId_grupo(), which exists in my Group.class:
public class Grupos {
Integer id_grupo;
String descricao;
public Grupos() {
}
public Grupos(Integer id_grupo, String descricao) {
this.id_grupo = id_grupo;
this.descricao = descricao;
}
public Grupos(Integer id_grupo) {
this.id_grupo = id_grupo;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public Integer getId_grupo() {
return id_grupo;
}
public void setId_grupo(Integer id_grupo) {
this.id_grupo = id_grupo;
}
}
I am calling my List list(Grupos groups) method in my ManagedBean
public class UsuariousGruposBean implements Serializable {
private Usuarious user = new Usuarious();
private Grupos grps = new Grupos();
private UsuariousGrupos userGroups = new UsuariousGrupos();
protected final UsuariousDAO userDAO = daoFactory.getUserDAO();
protected final GruposDAO grpDAO = daoFactory.getGruposDAO();
protected final UsuariousGruposDAO userGrpDAO = daoFactory.getUsuariousGruposDAO();
private List<Usuarious> listOfUsuarios;
private List<Grupos> listOfGrps;
private List<UsuariousGrupos> listOfUserGroups;
public UsuariousGruposBean() {
}
public List<Usuarious> getListOfUsuarios() throws DAOExceptions {
List<Usuarious> usuariosList = userDAO.list(grps);
listOfUsuarios = usuariosList;
return listOfUsuarios;
}

First instance in your code can throw NPE is at:
preparedStatement = connection.prepareStatement(SQL_LIST_ALL);
if your connection is null, your connection factory didnt return you one, check if you have a valid connection
Second place :
groups.getId_grupo()
Check if your groups is null or not
If these are not the reasons then please post your stacktrace.

The stack trace of your NPE should help tell you where the issue is (line #, etc.). From what I can tell, your SQL and the way you are calling it is all valid.
Is it possible that you're receiving a null groups parameter, such that calling groups.getId_grupo() is throwing the NPE?

Related

Testing a method that returns null at the end

public class CustomerDAO implements Dao<Customer> {
public static final Logger LOGGER = LogManager.getLogger();
#Override
public Customer modelFromResultSet(ResultSet resultSet) throws SQLException {
Long id = resultSet.getLong("id");
String firstName = resultSet.getString("firstName");
String surname = resultSet.getString("surname");
return new Customer(id, firstName, surname);
}
#Override
public Customer create(Customer customer) {
try (Connection connection = DBUtils.getInstance().getConnection();
PreparedStatement statement = connection
.prepareStatement("INSERT INTO customers(firstName, surname) VALUES (?, ?)");) {
statement.setString(1, customer.getFirstName());
statement.setString(2, customer.getSurname());
statement.executeUpdate();
return readLatest();
} catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return null;
}
}
The create method above is the one I am trying to test.
public class CustomerDAOTest {
private final CustomerDAO DAO = new CustomerDAO();
#Test
public void testCreate() {
final Customer created = new Customer(2L, "chris", "perrins");
assertEquals(created, DAO.create(created));
}
}
This is the test I wrote, but obviously the create method will return null, and the created variable won't, therefore the test fails. What can I do to work around this? The original method is not my own code, it's a learning exercise, so ideally I wouldn't want to change it that much if that's a possibility.
Well you could use assertNull:
assertNull(Dao.create(created));

BeanUtils.setProperty method sets null a BigDecimal field

I'm having a problem using the BeanUtils.setProperty method.
I'm using this JAR:
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
I run a MySQL query that returns one record and I'm mapping the resultset to a JavaBean that I've made.
Here you have the main class.
public class QueryTester {
public static void viewTable(Connection con) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {
Statement stmt = null;
String query = "SELECT * FROM Books WHERE code = 'AA00'";
try {
stmt = (Statement) con.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMapper<Books> rsMapper = new ResultSetMapper<Books>();
List<Books> list = rsMapper.mapResultSetToObject(rs, Books.class);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
stmt.close();
}
}
}
public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:mysql://localhost/dbname";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = (Connection) DriverManager.getConnection(url,userName,password);
viewTable(conn);
conn.close();
} catch (Exception e) {
System.out.println("NO CONNECTION");
}
}
}
And this is the method that uses the BeanUtils.setProperty method.
public class ResultSetMapper<T> {
public List<T> mapResultSetToObject(ResultSet rs, Class<T> outputClass) throws InstantiationException, SQLException, IllegalAccessException, InvocationTargetException {
List<T> outputList = new ArrayList<T>();
if (rs == null) {
return outputList;
}
if (!outputClass.isAnnotationPresent(Entity.class)) {
throw new InstantiationException("Entity notation not present.");
}
ResultSetMetaData rsmd = rs.getMetaData();
// retrieve data fields from output class
Field[] fields = outputClass.getDeclaredFields();
while (rs.next()) {
T bean = (T) outputClass.newInstance();
for (int iterator = 0; iterator < rsmd.getColumnCount(); iterator++) {
String columnName = rsmd.getColumnName(iterator + 1);
Object columnValue = rs.getObject(iterator + 1);
for (Field field : fields) {
if (field.isAnnotationPresent(Column.class)) {
Column column = field.getAnnotation(Column.class);
if (column.name().equalsIgnoreCase(columnName) && columnValue != null) {
BeanUtils.setProperty(bean, field.getName(), columnValue);
break;
}
}
}
}
outputList.add(bean);
}
return outputList;
}
}
mapResultSetToObject method returns a List with one element that is correct but the bean is set in a wrong way.
The fields code and bookDescription are set right but kPrice field is set null instead of 3.000 that is the value from database.
I run this code in debug mode and "columnValue" variable's value is 3.000 but the setProperty method doesn't set the right value and the value remains null.
Here you have my Java Bean.
#Entity
public class Books {
#Column(name="code")
private String code;
#Column(name="book_description")
private String bookDescription;
#Column(name="kPrice")
private BigDecimal kPrice;
public Books() {}
public Books(String code, String bookDescription, BigDecimal kPrice){
this.code = code;
this.bookDescription = bookDescription;
this.kPrice = kPrice;
}
/* Getters and setters */
...
}
And this is the MySQL table and the record.
CREATE TABLE `Books` (
`code` varchar(4) NOT NULL,
`book_description` varchar(50) NOT NULL DEFAULT '',
`kPrice` decimal(10,4) NOT NULL DEFAULT '1.0000',
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
INSERT INTO dbname.Books (code, book_description, kPrice) VALUES('AA00', 'Description example', 3.0000);
Why I get this behaviour? What am I missing?
Thanks in advance
Are you sure which the name of setters/getters is the same of property?
In some case, the problem is that.
See my example below:
#Entity
public class Books {
#Column(name="code")
private String code;
#Column(name="book_description")
private String bookDescription;
#Column(name="kPrice")
private BigDecimal kPrice;
public Books() {}
public Books(String code, String bookDescription, BigDecimal kPrice){
this.code = code;
this.bookDescription = bookDescription;
this.kPrice = kPrice;
}
public void setKPrice ( Bigdecimal kPrice) // and not setkPrice or setPrice..
{
this.kPrice = kPrice;
}
public BigDecimal getKPrice () // and not getkPrice or getPrice..
{
return this.kPrice;
}
}

Error when no constructor method and error when constructor method

im having a problem with my tableview. whenever i add a item to my database, it appears on my tableview, but only after i close and reopen the tableview. However i'd like to have added to my tableview immediately after having it added. So i made a refresh method, but im getting error from there. I have added comments to my code, which explains where the problem occurs.
I have removed imports and #FXML tags
package packet;
public class DataControll implements Initializable {
private static Connection con;
private static Statement stat;
private PreparedStatement prep;
ResultSet rs = null;
private ObservableList<Toidubaas> toidudata;
public void eemaldaListist() {
}
public void lisaNupp(ActionEvent event) {
try {
String query = "INSERT OR IGNORE INTO Toiduinfo (Toidu, Kalorid, Valgud, Süsivesikud, Rasvad) VALUES(?, ?, ?, ?, ?)";
prep = con.prepareStatement(query);
prep.setString(1, lisaToit.getText());
prep.setInt(2, Integer.parseInt(lisaKcal.getText()));
prep.setInt(3, Integer.parseInt(lisaValk.getText()));
prep.setInt(4, Integer.parseInt(lisaSysi.getText()));
prep.setInt(5, Integer.parseInt(lisaRasv.getText()));
prep.execute();
prep.close();
} catch (Exception er) {
System.out.println(er.getMessage());
}
clearForm();
}
private void clearForm() {
lisaToit.clear();
lisaKcal.clear();
lisaValk.clear();
lisaSysi.clear();
lisaRasv.clear();
}
#Override
public void initialize(URL url, ResourceBundle rb) {
toidudata = FXCollections.observableArrayList();
tbCal.setCellValueFactory(new PropertyValueFactory<Toidubaas, Integer>("rbCal"));
tbProt.setCellValueFactory(new PropertyValueFactory<Toidubaas, Integer>("rbProt"));
tbCarb.setCellValueFactory(new PropertyValueFactory<Toidubaas, Integer>("rbCarb"));
tbFat.setCellValueFactory(new PropertyValueFactory<Toidubaas, Integer>("rbFat"));
tbMeal.setCellValueFactory(new PropertyValueFactory<Toidubaas, String>("rbMeal"));
try {
con = DriverManager.getConnection("jdbc:sqlite:Fooditabel.sqlite");
stat = con.createStatement();
stat.executeUpdate(
"CREATE TABLE IF NOT EXISTS Toiduinfo (Toidu TEXT, Kalorid INTEGER, Valgud INTEGER, Süsivesikud INTEGER, Rasvad INTEGER)");
ResultSet rs = con.createStatement()
.executeQuery("SELECT Toidu, Kalorid, Valgud, Süsivesikud, Rasvad FROM Toiduinfo");
while (rs.next()) {
Toidubaas nt = new Toidubaas(); //if i add constructor method, im getting error here, saying the constructor is undefined
nt.rbMeal.set(rs.getString("Toidu"));
nt.rbCal.set(rs.getInt("Kalorid"));
nt.rbProt.set(rs.getInt("Valgud"));
nt.rbCarb.set(rs.getInt("Süsivesikud"));
nt.rbFat.set(rs.getInt("Rasvad"));
toidudata.add(nt);
}
tbTabelview.setItems(toidudata);
} catch (SQLException ex) {
System.out.println(ex.getMessage());
;
}
}
public void refreshTable() {
toidudata.clear();
try {
String query = "Select * FROM Toiduinfo";
prep = con.prepareStatement(query);
rs = prep.executeQuery();
while (rs.next()) {
toidudata.add(new Toidubaas( //Getting error here, if im not using constructor method, saying the method is undefined.
rs.getString("Toidu"),
rs.getInt("Kalorid"),
rs.getInt("Valgud"),
rs.getInt("Süsivesikud"),
rs.getInt("Rasvad")));
tbTabelview.setItems(toidudata);
}
prep.close();
} catch (Exception e2) {
}
}
}
and here is the class with constructor method. Please note that constructor method is commented out, so my program would populate tableview with database data.
public class Toidubaas {
public SimpleIntegerProperty rbCal = new SimpleIntegerProperty();
public SimpleIntegerProperty rbProt = new SimpleIntegerProperty();
public SimpleIntegerProperty rbCarb = new SimpleIntegerProperty();
public SimpleIntegerProperty rbFat = new SimpleIntegerProperty();
public SimpleStringProperty rbMeal = new SimpleStringProperty();
//This is the constructor method
/*public Toidubaas(String sbMeal, Integer sbCal, Integer sbProt, Integer sbCarb, Integer sbFat) {
this.rbMeal = new SimpleStringProperty(sbMeal);
this.rbCal = new SimpleIntegerProperty(sbCal);
this.rbProt = new SimpleIntegerProperty(sbProt);
this.rbCarb = new SimpleIntegerProperty(sbCarb);
this.rbFat = new SimpleIntegerProperty(sbFat);
}*/
public String getRbMeal() {
return rbMeal.get();
}
public void setRbMeal(String v) {
rbMeal.set(v);
}
public Integer getRbCal() {
return rbCal.get();
}
public void setRbCal(Integer v) {
rbCal.set(v);
}
public Integer getRbProt() {
return rbProt.get();
}
public void setRbProt(Integer v) {
rbProt.set(v);
}
public Integer getRbCarb() {
return rbCarb.get();
}
public void setRbCarb(Integer v) {
rbCarb.set(v);
}
public Integer getRbFat() {
return rbFat.get();
}
public void setRbFat(Integer v) {
rbFat.set(v);
}
}
It's really confusing what you're asking here. I'd recommend posting the actual error text rather than leaving in-code comments.
So you're attempting to use Toidubaas in two separate ways:
First (Empty Constructor)
Toidubaas nt = new Toidubaas(); //if i add constructor method, im getting error here, saying the constructor is undefined
nt.rbMeal.set(rs.getString("Toidu"));
nt.rbCal.set(rs.getInt("Kalorid"));
nt.rbProt.set(rs.getInt("Valgud"));
nt.rbCarb.set(rs.getInt("Süsivesikud"));
nt.rbFat.set(rs.getInt("Rasvad"));
toidudata.add(nt);
Second (Parameterized Constructor)
toidudata.add(new Toidubaas( //Getting error here, if im not using constructor method, saying the method is undefined.
rs.getString("Toidu"),
rs.getInt("Kalorid"),
rs.getInt("Valgud"),
rs.getInt("Süsivesikud"),
rs.getInt("Rasvad")));
tbTabelview.setItems(toidudata);
There's two ways to handle this: either standardize how you access this (IE: change the code in first to second, or vica versa), or support both methods.
Toidubaas
public class Toidubaas {
public SimpleIntegerProperty rbCal = new SimpleIntegerProperty();
public SimpleIntegerProperty rbProt = new SimpleIntegerProperty();
public SimpleIntegerProperty rbCarb = new SimpleIntegerProperty();
public SimpleIntegerProperty rbFat = new SimpleIntegerProperty();
public SimpleStringProperty rbMeal = new SimpleStringProperty();
//Empty Constructor (only need this if standardized to first approach)
public Toidubaas() {}
//Parameterized Constructor (only need this if standardized to second approach)
public Toidubaas(String sbMeal, Integer sbCal, Integer sbProt, Integer sbCarb, Integer sbFat) {
rbMeal.set(sbMeal);
rbCal.set(sbCal);
rbProt.set(sbProt);
rbCarb.set(sbCarb);
rbFat.set(sbFat);
}
//Getters/Setters
...
}
If you do not want to add a constructor with parameters, set the values one by one by calling the setters. It's also possible to overload the constructor (you shouldn't create the properties more than once though).
The row is not added to the TableView, since you never add it in case you submit the data successfully, which is pretty simple to fix though:
String query = "INSERT OR IGNORE INTO Toiduinfo (Toidu, Kalorid, Valgud, Süsivesikud, Rasvad) VALUES(?, ?, ?, ?, ?)";
try (PreparedStatement prep = con.prepareStatement(query)) {
String toidu = lisaToit.getText();
int kalorid = Integer.parseInt(lisaKcal.getText());
int valgud = Integer.parseInt(lisaValk.getText());
int süsivesikud = Integer.parseInt(lisaSysi.getText());
int rasvad = Integer.parseInt(lisaRasv.getText());
prep.setString(1, toidu);
prep.setInt(2, kalorid);
prep.setInt(3, valgud);
prep.setInt(4, süsivesikud);
prep.setInt(5, rasvad);
if (prep.executeUpdate() > 0) {
// object filled with data from input data
Toidubaas newToidubaas = new Toidubaas(toidu,
kalorid,
valgud,
süsivesikud,
rasvad);
// add new item to table here
toidudata.add(newToidubaas);
}
clearForm();
} catch (Exception er) {
System.out.println(er.getMessage());
}

How to retrieve and/or add database table values and display in the textfield

computeHandler.java
public class computeHandler extends DBCollection
{
private int totalcapitalPrice, totalprice;
public void setTotalCapitalPrice(int temp)
{
this.totalcapitalPrice = temp;
}
public void setTotalPrice(int temp)
{
this.totalprice = temp;
}
public int getTotalCapitalPrice()
{
return this.totalcapitalPrice;
}
public int getTotalPrice()
{
return this.totalprice;
}
}
where do I put the
SELECT SUM(Capital_Price) FROM item_list
and
SELECT SUM(Price) FROM item_list
I have a class named DBCollection which extends DBConnection and connects my codes to my database...
DBCollection.java
public class DBCollection extends DBConnection{
private Connection connect = null;
private ResultSet rs = null;
private Statement stmt = null;
public DBCollection()
{
try
{
connect = super.getConnection();
stmt = connect.createStatement();
//JOptionPane.showMessageDialog(null,"Connected!");
}
catch(Exception ex)
{
//JOptionPane.showMessageDialog(null,"Not Connected!");
}
}
private void closeConnection()
{
super.closeConnection(connect);
super.closeRecordSet(rs);
super.closeStatement(stmt);
}
I want to sum up all of the saved Capital_Price and Price values in my database.. and retrieve it to capitalPriceTF (textfield) and priceTF (textfield also).. how do I do that?
I also want to retrieve the First_name of the saved user... and display it to the Welcome(first name of user)..
You need to execute your query using Statement object:
So from statement object :
stmt = connect.createStatement();
Execute Your queries like this :
rs = stmt.executeQuery("SELECT SUM(Capital_Price) sum FROM item_list");
ResultSet rs object holds the retrieved data from by that query, so you can get the data like:
int sum = rs.getInt("sum");
Then what all you have to do, just organize your code based on the above and you will get every thing works just fine.

Java DAO classes for many-to-one relationship

I have a problem regarding how to save the objects in the Database in Java when having many-to-one relationship.
Basically I have 2 classes - UserVO and GroupVO, that look like this:
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
// ...
}
and
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
// ...
}
Their super-class is a very simple abstract class:
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
// ...
}
Now I have to create the DAO classes for them. In the UserDAO I something like this for creating and inserting a user in the 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();
}
There are also some helper Classes, but I guess you understand my code :).
And this is the GroupDAO create method:
#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();
}
Now, if I make a small test in the main function, for creating a group and saving in the DB, everything goes well:
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);
As GroupVO class has a set of UserVO objects, and in the main function if I also type:
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
and say I am first time calling: dao.create(group1);
Normally, this shouldn't only save the Group info, but also all the associated UserVO objects.
For me that means that in the "create" function of the GroupDAO, after the group ID is successfully generated, I need to do a lot of other code.
I wonder is this is the correct way of saving those users in the DB, as I think I have to make the GroupDAO class to communicate with the UserDAO class, and also with the DAOFactory, which in my case, can give us an UserDAO, or GroupDAO object. Or I can do all the DB interection for saving those users without using the UserDAO class.
That code that I'm thinking seem very long, messy/spaghetti, and I am not quite sure if this is the correct approach :(.
Note that I am note using any ORM Framework.
Please let me know guys, what do you think about that?!
If you need more details, I can send you my Project, it's not commercial :D
Thanks in advance
I would use a GroupDAO to only create the group, a UserDAO to only create a user, and a functional service delegating to these two DAOs to create a group with all its users. Its code would look like the following:
Long groupId = groupDao.createGroup(groupVO);
for (UserVO userVO : groupVO.getUsers()) {
userDao.createUser(userVO, groupId);
}

Categories