简体   繁体   English

如何用jdbc实现一对多

[英]How to implement one to many with jdbc

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. 我没有使用Spring,只有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? 没有Spring,Hibernate和其他东西,有可能做到这一点吗? I just want to know how design my program. 我只想知道如何设计程序。

Yes, you can do everything just with a JDBC database driver. 是的,您只需使用JDBC数据库驱动程序就可以完成所有操作。

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. 然后,您返回Java并使用JDBC查询数据库。

A common approach to this is creating a DAO class, where you can decouple your database query from your code. 一种常见的方法是创建DAO类,您可以在其中将数据库查询与代码分离。 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. 这只是一个简单的示例,这里没有错误处理,也没有处理空的查询结果,在线上有更好的示例来说明如何制作DAO和创建连接。 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. 在您的用例中,您将让DAO获得数据来制作Item ,创建一个新Item并从DAO返回它。 There are plenty of examples of this online, if you have further questions, don't hesitate to ask. 在线上有很多示例,如果您还有其他问题,请随时提出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM