Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public interface IUser {
- ArrayList<UserBean> getUsers() throws SQLException;
- }
- public class User implements IUser {
- private DataSource dataSource;
- public User() {
- dataSource = Connection.getDataSource();
- }
- @Override
- public ArrayList<UserBean> getUsers() throws SQLException {
- PreparedStatement preparedStatement = null;
- ResultSet resultSet = null;
- ArrayList<UserBean> userBeans = new ArrayList<>();
- try (Connection connection = dataSource.getConnection()) {
- preparedStatement = connection.prepareStatement("SELECT user.id, user.emailAddress FROM user");
- resultSet = preparedStatement.executeQuery();
- while(resultSet.next()) {
- UserBean userBean = new UserBean(resultSet.getInt("user.id"), resultSet.getString("user.emailAddress"));
- userBeans.add(userBean);
- }
- } finally {
- if(preparedStatement != null) preparedStatement.close();
- if(resultSet != null) resultSet.close();
- }
- return userBeans;
- }
- }
- public class UserBean implements Serializable {
- private int id;
- private String emailAddress;
- public UserBean(int id, String emailAddress) {
- this.id = id;
- this.emailAddress = emailAddress;
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getEmailAddress() {
- return emailAddress;
- }
- public void setEmailAddress(String emailAddress) {
- this.emailAddress = emailAddress;
- }
- }
- public class Connection {
- private static MysqlDataSource dataSource;
- public synchronized static MysqlDataSource getDataSource() {
- if (dataSource != null) return dataSource;
- dataSource = new MysqlDataSource();
- if(System.getenv("DEVELOPMENT") != null) {
- dataSource.setURL("jdbc:mysql://localhost:3306/Sales?authReconnect=true&useSSL=false&allowMultiQueries=true&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC");
- dataSource.setUser("root");
- dataSource.setPassword("pass1");
- } else {
- dataSource.setURL("jdbc:mysql://foo.bar.rds.example.com:3306/Entitlement?authReconnect=true&useSSL=false&allowMultiQueries=true");
- dataSource.setUser("root");
- dataSource.setPassword("pass2");
- }
- return dataSource;
- }
- }
Add Comment
Please, Sign In to add comment