Java Reference
In-Depth Information
// Just a normal line
currentOffset += 1;
return Optional.of(
new TextLine(currentTitle, currentYear, currentOffset, s)
);
}
}
### DatabaseLineMapper.java
import java.sql.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
/**
* Responsible for mapping text lines into database lines.
*/
public class DatabaseLineMapper implements Function<TextLine, DatabaseLine> {
private final ConcurrentMap<String, Integer> textIds =
new ConcurrentHashMap<>();
private final ConcurrentMap<Integer, ConcurrentMap<Integer, Integer>>
textLineIds = new ConcurrentHashMap<>();
private final ConcurrentMap<String, Integer> wordIds =
new ConcurrentHashMap<>();
private final Database database;
public DatabaseLineMapper(Database database) throws SQLException {
Objects.requireNonNull(database, "database");
this.database = database;
}
private int computeTextId(String title, int year) {
try (Connection conn = database.getConnection()) {
PreparedStatement createBook = conn.prepareStatement(
"INSERT INTO \"text\" (name, year) VALUES (?,?)",
Statement.RETURN_GENERATED_KEYS
);
createBook.setString(1, title);
createBook.setInt(2, year);
boolean createdBook = createBook.executeUpdate() == 1;
assert createdBook : "Could not create book";
try (ResultSet rs = createBook.getGeneratedKeys()) {
boolean hasNext = rs.next();
assert hasNext : "No result when getting generated keys for " + title;
return rs.getInt(1);
}
} catch (SQLException e) {
throw new RuntimeException(
"error while computing text id for: " + title, e);
}
}
Search WWH ::




Custom Search