有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javaee中书店应用逻辑的mysql问题

我在做书店,到目前为止我只有3张桌子

Book:
- id:(int) primary key, autoincrement, not null,
- title:(varchar) not null,
- price: (decimal) not null

Cart:
-id:(int) primary key, autoincrement, not null 

Article:
- id:(int) primary key, autoincrement, not null,
- title:(varchar) not null,
- price: (decimal) not null,
- cart_id:(int) foreign key referencing cart

对我来说,当用户点击“添加到购物车”按钮检查购物车是否已经存在是合乎逻辑的,如果已经存在,我将返回该购物车,如果不创建新的。用户将在一个购物车中放置多个物品。这是我在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);
           }

在CartDAO中,我希望有这样的支票:

if(cart == null){
'insert into cart()values()'
}else{ // if cart exist i want to return that cart id}

我不知道如何使用生成的密钥来实现这一点

下面是我在ArticleDAO中从cart传递id的类

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

我的问题是什么是进行检查的正确方法?也许是和session?如果购物车存在,如何返回id?我知道这是一个很长的问题,但我认为对任何有java工作经验的人来说都很容易。感谢所有花时间阅读并回答此问题的人


共 (0) 个答案