Enterprise Java Development@TOPIC@
public class JDBCBookDAOImpl implements BookDAO {
private Connection connection;
public void setConnection(Connection connection) {
this.connection = connection;
}
@Override
public Book create(Book book) throws PersistenceException {
try (PreparedStatement insertStatement=getInsertPreparedStatement(connection, book);
PreparedStatement idStatement=getIdentityStatement(connection)){
insertStatement.execute();
try (ResultSet rs = idStatement.executeQuery()) {
if (rs.next()) {
Field id = Book.class.getDeclaredField("id");
id.setAccessible(true);
id.set(book, rs.getLong(1));
} else {
throw new PersistenceException("no identity returned from database");
}
} catch (NoSuchFieldException ex) {
throw new PersistenceException("Error locating id field", ex);
} catch (IllegalAccessException ex) {
throw new PersistenceException("Access error setting id", ex);
}
return book;
} catch (SQLException ex) {
throw new PersistenceException("SQL error creating book", ex);
}
}
...
}
private PreparedStatement getInsertPreparedStatement(Connection c, Book book) throws SQLException {
PreparedStatement statement=connection.prepareStatement(
"insert into JPADAO_BOOK (ID, DESCRIPTION, PAGES, TITLE) " +
"values (null, ?, ?, ?)");
statement.setString(1, book.getDescription());
statement.setInt(2, book.getPages());
statement.setString(3, book.getTitle());
return statement;
}
private PreparedStatement getIdentityStatement(Connection c) throws SQLException {
PreparedStatement statement = connection.prepareStatement("call identity()");
return statement;
}
public class JPANativeSQLBookDAO implements BookDAO {
private EntityManager em;
public void setEntityManager(EntityManager em) {
this.em = em;
}
@Override
public Book create(Book book) throws PersistenceException {
em.createNativeQuery(
"insert into JPADAO_BOOK (ID, DESCRIPTION, PAGES, TITLE) " +
"values (null, ?1, ?2, ?3)")
.setParameter(1, book.getDescription())
.setParameter(2, book.getPages())
.setParameter(3, book.getTitle())
.executeUpdate();
int idVal = ((Number)em.createNativeQuery("call identity()")
.getSingleResult()).intValue();
try {
Field id = Book.class.getDeclaredField("id");
id.setAccessible(true);
id.set(book, idVal);
} catch (Exception ex) {
throw new RuntimeException("Error setting id", ex);
}
return book;
}
...
}