Guest User

Untitled

a guest
Mar 27th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.45 KB | None | 0 0
  1. public interface IUser {
  2. ArrayList<UserBean> getUsers() throws SQLException;
  3. }
  4.  
  5. public class User implements IUser {
  6.  
  7. private DataSource dataSource;
  8.  
  9. public User() {
  10. dataSource = Connection.getDataSource();
  11. }
  12.  
  13. @Override
  14. public ArrayList<UserBean> getUsers() throws SQLException {
  15. PreparedStatement preparedStatement = null;
  16. ResultSet resultSet = null;
  17. ArrayList<UserBean> userBeans = new ArrayList<>();
  18. try (Connection connection = dataSource.getConnection()) {
  19. preparedStatement = connection.prepareStatement("SELECT user.id, user.emailAddress FROM user");
  20. resultSet = preparedStatement.executeQuery();
  21.  
  22. while(resultSet.next()) {
  23. UserBean userBean = new UserBean(resultSet.getInt("user.id"), resultSet.getString("user.emailAddress"));
  24. userBeans.add(userBean);
  25. }
  26. } finally {
  27. if(preparedStatement != null) preparedStatement.close();
  28. if(resultSet != null) resultSet.close();
  29. }
  30. return userBeans;
  31. }
  32. }
  33.  
  34. public class UserBean implements Serializable {
  35.  
  36. private int id;
  37. private String emailAddress;
  38.  
  39. public UserBean(int id, String emailAddress) {
  40. this.id = id;
  41. this.emailAddress = emailAddress;
  42. }
  43.  
  44. public int getId() {
  45. return id;
  46. }
  47.  
  48. public void setId(int id) {
  49. this.id = id;
  50. }
  51.  
  52. public String getEmailAddress() {
  53. return emailAddress;
  54. }
  55.  
  56. public void setEmailAddress(String emailAddress) {
  57. this.emailAddress = emailAddress;
  58. }
  59.  
  60. }
  61.  
  62. public class Connection {
  63.  
  64. private static MysqlDataSource dataSource;
  65.  
  66. public synchronized static MysqlDataSource getDataSource() {
  67. if (dataSource != null) return dataSource;
  68.  
  69. dataSource = new MysqlDataSource();
  70. if(System.getenv("DEVELOPMENT") != null) {
  71. dataSource.setURL("jdbc:mysql://localhost:3306/Sales?authReconnect=true&useSSL=false&allowMultiQueries=true&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC");
  72. dataSource.setUser("root");
  73. dataSource.setPassword("pass1");
  74. } else {
  75. dataSource.setURL("jdbc:mysql://foo.bar.rds.example.com:3306/Entitlement?authReconnect=true&useSSL=false&allowMultiQueries=true");
  76. dataSource.setUser("root");
  77. dataSource.setPassword("pass2");
  78. }
  79.  
  80. return dataSource;
  81. }
  82.  
  83. }
Add Comment
Please, Sign In to add comment