Reputation: 85
I'm trying to write a program to manage some clients. Each client has reservations, and each reservation has items.I know that I have one to many relationship, but I cannot figure out how to do that.
I'm not using Spring, only JDBC.
Without a database I did it like that:
public class Client {
private String _fullName;
private String _address;
private String _email;
private String _phoneNumber;
private List<Reservation> _reservations;
}
public class Reservation {
private List<Item> _items;
private int _totalSum;
private boolean _toDeliver;
private String _date;
}
public class Item {
//primary key.
private int _id;
private int _price;
private String _name;
}
Do I have to declare these Lists? Is it possible to do that without Spring, Hibernate and other stuff? I just want to know how design my program.
Upvotes: 0
Views: 1893
Reputation: 14304
Yes, you can do everything just with a JDBC database driver.
The first thing you have to do is to design your database, that is your tables and constraints and etc.
Then you go back to Java and query your database using the JDBC.
A common approach to this is creating a DAO class, where you can decouple your database query from your code. It goes something like this:
public String getUserName(String userId) throws SQLException {
String sql = "SELECT name FROM user WHERE user_id = ?";
try (Connection connection = getConnection();
PreparedStatement stmt = connection.prepareStatement(sql)) {
stmt.setString(1, userId);
try (ResultSet rs = stmt.executeQuery()) {
String name = rs.getString("name");
return name;
}
}
}
This is just a simple example, there's no error handling here, neither dealing with empty query results, there are better examples online to illustrate how to make a DAO and create a connection. Depending on where you are running this code, you would prefer using a Connection Pool for efficiency (another thing to read more about).
In your use case, you would have the DAO get the data to make your Item
, create a new Item
and return it from the DAO. There are plenty of examples of this online, if you have further questions, don't hesitate to ask.
Upvotes: 1