问题
I'm making book store and so far i only have 3 tables.
Book:
- id:(int) primary key, autoincrement, not null,
- title:(varchar) not null,
- price: (decimal) not null
Cart:
-id:(int) primary key, autoincrement, not null
and
Article:
- id:(int) primary key, autoincrement, not null,
- title:(varchar) not null,
- price: (decimal) not null,
- cart_id:(int) foreign key referencing cart
For me it's logical when user clicks on "add to cart" button to check if cart already exist, if exist i will return that cart if not create new. And user will put multiple articles in one cart. This is my class for inserting Cart in db:
public class CartDAO {
private static DataSource dataSource;
private static int autoIncKey = -1;
public static void insertCart() {
Connection conn = null;
ResultSet rs = null;
try {
InitialContext ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup("jdbc/NemkeDB");
conn = dataSource.getConnection();
String insert = "insert into cart() values()";
PreparedStatement ps = conn.prepareStatement(insert, RETURN_GENERATED_KEYS);
ps.executeUpdate();
rs = ps.getGeneratedKeys();
if (rs.next()) {
autoIncKeyFromApi = rs.getInt(1);
} catch(Exception e){
System.err.println(e);
}
In CartDAO i want to have that check, something like this:
if(cart == null){
'insert into cart()values()'
}else{ // if cart exist i want to return that cart id}
i don't know how to do that with GeneratedKeys.
Below is the class where i'm passing the id from cart in ArticleDAO
public class ArticleDAO {
private static DataSource dataSource;
private static ArrayList<Article> articleList = new ArrayList<>();
public static void insertArticle(String title, double price) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
InitialContext ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup("jdbc/NemkeDB");
conn = dataSource.getConnection();
st = conn.createStatement();
CartDAO.insertCart(); // Here is where i call(insert) Cart
String insert = "insert into article(title,price,cart_id) values(?,?,?)";
PreparedStatement ps = conn.prepareStatement(insert);
ps.setString(1, title);
ps.setDouble(2, price);;
ps.setInt(3, CartDAO.getAutoIncKey()); // Here i pass that id
ps.executeUpdate();
rs = st.executeQuery("select * from artical");
while (rs.next()) {
String articalTitle = rs.getString("title");
double articalPrice = rs.getDouble("price");
Artical artical = new Artical(articalTitle, articalPrice);
articalList.add(artical);
}
} catch (Exception e) {
System.err.println(e);
}
My question is what is the proper way to make that check? Maybe with session? And how to return id if cart exist? I know it's a long question but i think it's easy for anyone with any working experience with java. Thanks everyone who invested time to read and reply this problem.
来源:https://stackoverflow.com/questions/62853215/problem-with-logic-of-book-store-application-in-java-ee