Java DAO classes for many-to-one relationship - java

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);
}

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));

Java Return Null When Tried to Get Method

first of all I know this is duplicated question. But I've search and tried from stackoverflow listed on Google to quora but still cant resolve my Get method still return null.
This is my class loginModel.java under package com.hello.model
public class loginModel {
public String username;
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return this.username;
}
}
This is my loginView.java under package com.hello.view
import com.hello.model.loginModel;
public class loginView extends javax.swing.JFrame {
loginModel login = new loginModel();
public loginView() {
initComponents();
this.setLocationRelativeTo(null);
loginFunction();
}
private void loginFunction(){
String username = usernameText.getText();
String password = passwdText.getText();
String query = "select * from access where username = '" +username+ "' AND password = '" +password+"'";
databaseConnect db = new databaseConnect();
try (Connection con = DriverManager.getConnection(db.url, db.user, db.password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
if(rs.next()) {
if(username.equals(rs.getString("username")) && password.equals(rs.getString("password"))){
JOptionPane.showMessageDialog(null, "login Success");
String name = rs.getString("name");
String privilege = rs.getString("privilege");
login.setUsername(name);
menu = new menuView();
menu.setVisible(true);
this.setVisible(false);
}
} else {
JOptionPane.showMessageDialog(null, "username or password incorrect");
}
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
I want call my username from menuView.java under package com.hello.view after login success
import com.hello.model.loginModel;
import com.hello.view.loginView;
public class menuView extends javax.swing.JFrame {
private String username;
loginModel login = new loginModel();
public menuView() {
initComponents();
this.setLocationRelativeTo(null);
initMenu();
}
private void initMenu(){
username = login.getUsername();
JOptionPane.showMessageDialog(this, username);
}
}
As per my question when I call Get method from loginModel, messagebox return null.
I've tried:
Put system.out.println directly in loginModel.java, value return
and call system.out.println in menuView.java at the same time but value return null. How?
Send string between jframe with menu = menuView(username) in loginView.java and retrieve in menuView.java, value return null
Using no model and create set string in loginView and call it in
menuView, value return null
I need values that I want to use in another class/package/jframe. Am I doing wrong?
I am not well versed in Swing but I can see the problem, just not the exact solution.
Your code creates an instance of loginModel in both the menuView and in loginView. Then in loginView is sets the name in the instance it has, in in menuView it gets the name from its own instance.
You need to create a single instance of the model and share it between the two views.
In a pojo way I would pass the loginModel to both "views" in a constructor.
menu = new menuView(login);
And in menuView
public menuView(loginModel login) {
this.login = login;
}
Your menuView instance isn't using the loginModel class that you instantiate in loginView, it's using the new one you created using new menuView() when you initialized the login variable in the menuView class. You just need to add a setter method for the loginModel attribute in the menuView class like this:
import com.hello.model.loginModel;
import com.hello.view.loginView;
public class menuView extends javax.swing.JFrame {
private String username;
loginModel login = new loginModel();
public menuView() {
initComponents();
this.setLocationRelativeTo(null);
initMenu();
}
private void initMenu(){
username = login.getUsername();
JOptionPane.showMessageDialog(this, username);
}
public void setLogin(loginModel loginModel) {
this.login = loginModel;
}
}
Then call the setter in loginView.loginFunction like this:
... code before
login.setUsername(name);
menu = new menuView();
menu.setLogin(login);
menu.setVisible(true);
this.setVisible(false);
... code after
Notice the only changes to your code are the added setLogin method on the menuView class and the call to menu.setLogin(login) in loginView.loginFunction.
You need to think in stages/steps. Login is a single step, it has one of two outcomes, success or failure.
Your app needs to perform this step and take appropriate action based on the outcome of the result.
You also need to think about "separation of responsibility" - in this case, it's not really the responsibility of the loginView to perform the login operation, it just coordinates the user input.
The responsibility actually falls to the LoginModel
// Just a custom exception to make it easier to determine
// what actually went wrong
public class LoginException extends Exception {
public LoginException(String message) {
super(message);
}
}
// LoginModel ... that "does" stuff
public class LoginModel {
private String username;
DatabaseConnect db;
public LoginModel(DatabaseConnect db) {
this.db = db;
}
// I would consider not doing this. You need to ask what reasons would
// the app need this information and expose it only if there is really a
// reason to do so
public String getUsername() {
return username;
}
public boolean isLogedIn() {
return username != null;
}
public void validate(String username, String password) throws SQLException, LoginException {
String query = "select * from access where username = ? AND password = ?";
try ( Connection con = DriverManager.getConnection(db.url, db.user, db.password); PreparedStatement st = con.prepareStatement(query)) {
st.setString(1, username);
st.setString(2, password);
try ( ResultSet rs = st.executeQuery()) {
if (rs.next()) {
this.username = username;
} else {
throw new LoginException("Invalid user credentials");
}
}
}
}
}
This is an overly simplified example, as the actual responsibility for performing the login should fall to the controller, which would then generate the model, but I'm getting ahead of myself.
Because the flow of the app shouldn't be controlled/determined by the login view, the LoginView should itself be a dialog. This way, it can be shown when you need it, it can perform what ever operations it needs and then go away, leaving the rest of the decision making up to who ever called it
public class LoginView extends javax.swing.JDialog {
private LoginModel model;
public LoginView(LoginModel model) {
initComponents();
setModal(true);
this.model = model;
this.setLocationRelativeTo(null);
}
// This will get executed when the user taps some kind of "perform login button"
private void loginFunction() {
String username = usernameText.getText();
String password = passwdText.getText();
try {
model.validate(username, password);
dispose()
} catch (SQLException ex) {
// This should probably be considered a fatal error
model = null;
dispose();
} catch (LoginException ex) {
JOptionPane.showMessageDialog(this, "Login vaild");
}
}
}
This then means you might put it together something like this...
DatabaseConnect db = new DatabaseConnect();
LoginModel model = new LoginModel(db);
LoginView loginView = new LoginView(model);
// Because we're using a modal dialog, the code execution will wait here
// till the window is disposed/closed
loginView.setVisible(true);
if (loginView.model != null) {
// model is now valid and can continue to be used
// in what ever fashion you need
} else {
JOptionPane.showMessageDialog(null, "Fatal Error");
}
This takes you a step closer to a more decoupled solution, where you feed information to the classes when they need it, rather than the classes making decisions about what they should create/use.
It also moves you a step closer to re-usable classes, as they do their specific job and nothing more.
You might find taking the time to read up on "model-view-controller" will help you better understand this approach

Rest API returns an empty list when connecting to database using JDBC ignoring the data brought from the database

Im doing a project on my own and the point of the project is to make an a rest API in java and bring data from database using JDBC. The problem is when i make the connection and retrieve the data using main method everything works fine but when i try to retrieve the data through a get request, it returns an empty list. This is the endpoint
#Path("/users")
public class UserResource {
UserService userService = new UserService();
#GET
#Path("/all")
#Produces(MediaType.APPLICATION_JSON)
public Response getAllUsers() throws InterruptedException {
List<User> users = userService.getAllUsers();
GenericEntity<List<User>> wrapper = new GenericEntity<List<User>>(users) {
};
return Response.ok(wrapper).build();
}
}
And this is the class that connects to database using JDBC
public class ConnectionJDBC {
private static String USERNAME = "root";
private static String PASSWORD = "root";
private static String CONSTRING = "jdbc:mysql://localhost:3306/";
private static String DATABASE = "users_db";
static Connection connection;
public ConnectionJDBC() {
}
public static Connection getConnectionToDB() {
try {
String url = CONSTRING + DATABASE;
connection = DriverManager.getConnection(url, USERNAME, PASSWORD);
if (connection != null) {
System.out.println("Connected");
} else {
System.out.println("Connection faild");
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Something went wrong before establishing the connection");
}
return connection;
}
public List<User> getUsers() {
connection = getConnectionToDB();
String query = "SELECT * FROM users_db.user_info;";
List<User> userListRetrived = new ArrayList<>();
try {
PreparedStatement statement = connection.prepareStatement(query);
ResultSet dataRetrieved = statement.executeQuery();
while (dataRetrieved.next()) {
User user = new User(dataRetrieved.getInt("id"),
dataRetrieved.getString(2),
dataRetrieved.getString(3));
userListRetrived.add(user);
return userListRetrived;
}
} catch (Exception e) {
e.printStackTrace();
System.err.println("Something went wrong when retriving the data");
}
return userListRetrived;
}
}
UserService class is here
public class UserService {
private ConnectionJDBC connectionJDBC = new ConnectionJDBC();
public UserService() {
}
public List<User> getAllUsers() {
ConnectionJDBC connectionJDBC = new ConnectionJDBC();
List<User> usersList = connectionJDBC.getUsers();
return usersList;
}
}
The user class is a normal java bean. It feels like getUsers method is ignoring bringing the data from the database and instead it returns the instantiated empty list instead. I'm using jersey and deploying the project on Glassfish.
Any clues on how i can fix that or explanation for this situation?
Many thanks in advance!
You didn't invoke userService.getUsers() method from userResource() class. Please update your code in userResource() class as follows
GenericEntity<List<User>> wrapper = new GenericEntity<List<User>>(userService.getUsers());

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());
}

preparedstatement with sql query referencing multiple tables

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?

Categories