Junior — Middle
How can a record be retrieved from a database by its unique identifier?
sobes.tech AI
Answer from AI
To retrieve a record from a database by a unique identifier in Java, you typically use an SQL query with a condition on the primary key. For example, if you have a users table with an id field, you can execute a query:
String sql = "SELECT * FROM users WHERE id = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setInt(1, userId);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
// Retrieve data from rs
}
If using an ORM like Hibernate or JPA, you can get the object by its identifier like this:
User user = entityManager.find(User.class, userId);
Thus, the key point is to use the unique identifier in the query condition to fetch the specific record.