├── LICENSE ├── README.md ├── lib ├── commons-dbcp2-2.8.0.jar ├── commons-logging-1.2.jar ├── commons-pool2-2.9.0.jar ├── db │ ├── db4o-8.0.249.16098-all-java5.jar │ ├── derbyclient.jar │ ├── mysql-connector-java-8.0.22.jar │ ├── ojdbc14.jar │ └── postgresql-42.2.5.jar ├── javax.annotation-api-1.3.2.jar ├── jpa │ ├── eclipselink.jar │ └── jakarta.persistence_2.2.3.jar ├── spring-aop-5.3.0-sources.jar ├── spring-aop-5.3.0.jar ├── spring-beans-5.3.0-sources.jar ├── spring-beans-5.3.0.jar ├── spring-context-5.3.0-sources.jar ├── spring-context-5.3.0.jar ├── spring-core-5.3.0-sources.jar ├── spring-core-5.3.0.jar ├── spring-expression-5.3.0-sources.jar ├── spring-expression-5.3.0.jar ├── spring-jdbc-5.3.0-sources.jar ├── spring-jdbc-5.3.0.jar ├── spring-orm-5.3.0-sources.jar ├── spring-orm-5.3.0.jar ├── spring-tx-5.3.0-sources.jar └── spring-tx-5.3.0.jar └── src └── org └── javaturk └── spring └── data ├── ch01 └── Readme.txt ├── ch02 ├── Readme.txt ├── jdbc │ ├── basic │ │ ├── JdbcTest.java │ │ ├── dao │ │ │ └── PersonJdbcDAO.java │ │ ├── uml │ │ │ ├── CD1.png │ │ │ └── CD2.png │ │ └── util │ │ │ └── JdbcUtil.java │ ├── common │ │ ├── data │ │ │ └── PersonDAO.java │ │ ├── domain │ │ │ ├── Factory.java │ │ │ ├── Person.java │ │ │ ├── PersonFactory.java │ │ │ └── ex │ │ │ │ └── NoSuchPersonException.java │ │ └── resources │ │ │ ├── DB.sql │ │ │ └── jdbc.properties │ └── spring │ │ ├── SpringTest.java │ │ ├── conf │ │ ├── AppConfig.java │ │ └── JDBCConfig.java │ │ ├── dao │ │ ├── PersonJdbcConnectionDAO.java │ │ └── PersonJdbcDataSourceDAO.java │ │ └── uml │ │ └── CD.png └── spring │ ├── jdbcTemplate │ └── person │ │ ├── JdbcTemplateTest.java │ │ ├── callback │ │ ├── PersonPreparedStatementIdAndDobSetter.java │ │ ├── PersonPreparedStatementIdSetter.java │ │ ├── PersonPreparedStatementSetter.java │ │ └── PersonRowMapper.java │ │ ├── conf │ │ ├── AppConfig.java │ │ └── JDBCConfig.java │ │ ├── dao │ │ └── PersonJdbcTemplateDAO.java │ │ └── resources │ │ └── jdbc.properties │ ├── namedParameterJdbcTemplate │ └── person │ │ ├── NamedParameterJdbcTemplateTest.java │ │ ├── callback │ │ ├── PersonRowMapper.java │ │ └── PersonSqlParameterSource.java │ │ ├── conf │ │ ├── AppConfig.java │ │ └── JDBCConfig.java │ │ ├── dao │ │ └── PersonNamedParameterJdbcTemplateDAO.java │ │ └── resources │ │ └── jdbc.properties │ └── simpleJdbcInsert │ └── person │ ├── SimpleJdbcInsertTest.java │ ├── callback │ ├── PersonSqlParameterSource.java │ └── PersonSqlParameterSourceWithoutDob.java │ ├── conf │ ├── AppConfig.java │ └── JDBCConfig.java │ ├── dao │ ├── PersonInsertDao.java │ ├── SimpleJdbcInsertDao1.java │ └── SimpleJdbcInsertDao2.java │ └── resources │ └── jdbc.properties ├── ch03 ├── Readme.txt ├── common │ ├── dao │ │ └── PersonDao.java │ └── domain │ │ ├── Factory.java │ │ ├── Person.java │ │ ├── PersonFactory.java │ │ └── ex │ │ └── NoSuchPersonException.java ├── jpa │ ├── basic │ │ ├── PersonJpaDaoTest.java │ │ ├── dao │ │ │ └── PersonJpaDao.java │ │ ├── resources │ │ │ └── jpa.properties │ │ ├── uml │ │ │ └── CD.png │ │ └── util │ │ │ └── PersistenceUtil.java │ └── spring │ │ ├── PersonJpaDaoSpringTest.java │ │ ├── conf │ │ ├── AppConfig.java │ │ └── JPAConfig.java │ │ ├── dao │ │ ├── PersonDao.java │ │ └── PersonJpaSpringDao.java │ │ ├── domain │ │ ├── Factory.java │ │ ├── Person.java │ │ ├── PersonFactory.java │ │ └── ex │ │ │ └── NoSuchPersonException.java │ │ ├── resources │ │ └── jpa.properties │ │ └── uml │ │ └── CD.png ├── oodb │ ├── Db4oDaoTest.java │ └── PersonDb4oDAO.java └── spring │ ├── localContainerEMFBean │ ├── LocalContainerEntityManagerFactoryBeanTest.java │ ├── conf │ │ ├── AppConfig.java │ │ └── JPAConfig.java │ ├── dao │ │ └── PersonJpaSpringLCEMFBDao.java │ └── resources │ │ └── jpa.properties │ └── localEMFBean │ ├── LocalEntityManagerFactoryBeanTest.java │ ├── conf │ ├── AppConfig.java │ └── JPAConfig.java │ ├── dao │ ├── PersonDao.java │ └── PersonJpaSpringLEMFBDao.java │ └── resources │ └── jpa.properties └── ch04 └── repository ├── jdbc ├── basic │ ├── JdbcTest.java │ ├── dao │ │ └── PersonJdbcDAO.java │ ├── uml │ │ ├── CD1.png │ │ └── CD2.png │ └── util │ │ └── JdbcUtil.java └── jdbcTemplate │ └── person │ ├── JdbcTemplateRespositoryTest.java │ ├── conf │ ├── AppConfig.java │ └── JDBCConfig.java │ └── dao │ └── PersonJdbcTemplateDAO.java └── jpa └── localContainerEMFBean ├── LocalContainerEntityManagerFactoryBeanRepositoryTest.java ├── conf ├── AppConfig.java └── JPAConfig.java └── dao └── PersonJpaSpringLCEMFBDao.java /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 javaturk 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SpringData 2 | This is code example for Spring Data training. 3 | It might be a part of Spring training. 4 | For more info reach me akin@javaturk.org. 5 | -------------------------------------------------------------------------------- /lib/commons-dbcp2-2.8.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/commons-dbcp2-2.8.0.jar -------------------------------------------------------------------------------- /lib/commons-logging-1.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/commons-logging-1.2.jar -------------------------------------------------------------------------------- /lib/commons-pool2-2.9.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/commons-pool2-2.9.0.jar -------------------------------------------------------------------------------- /lib/db/db4o-8.0.249.16098-all-java5.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/db/db4o-8.0.249.16098-all-java5.jar -------------------------------------------------------------------------------- /lib/db/derbyclient.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/db/derbyclient.jar -------------------------------------------------------------------------------- /lib/db/mysql-connector-java-8.0.22.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/db/mysql-connector-java-8.0.22.jar -------------------------------------------------------------------------------- /lib/db/ojdbc14.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/db/ojdbc14.jar -------------------------------------------------------------------------------- /lib/db/postgresql-42.2.5.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/db/postgresql-42.2.5.jar -------------------------------------------------------------------------------- /lib/javax.annotation-api-1.3.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/javax.annotation-api-1.3.2.jar -------------------------------------------------------------------------------- /lib/jpa/eclipselink.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/jpa/eclipselink.jar -------------------------------------------------------------------------------- /lib/jpa/jakarta.persistence_2.2.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/jpa/jakarta.persistence_2.2.3.jar -------------------------------------------------------------------------------- /lib/spring-aop-5.3.0-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/spring-aop-5.3.0-sources.jar -------------------------------------------------------------------------------- /lib/spring-aop-5.3.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/spring-aop-5.3.0.jar -------------------------------------------------------------------------------- /lib/spring-beans-5.3.0-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/spring-beans-5.3.0-sources.jar -------------------------------------------------------------------------------- /lib/spring-beans-5.3.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/spring-beans-5.3.0.jar -------------------------------------------------------------------------------- /lib/spring-context-5.3.0-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/spring-context-5.3.0-sources.jar -------------------------------------------------------------------------------- /lib/spring-context-5.3.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/spring-context-5.3.0.jar -------------------------------------------------------------------------------- /lib/spring-core-5.3.0-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/spring-core-5.3.0-sources.jar -------------------------------------------------------------------------------- /lib/spring-core-5.3.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/spring-core-5.3.0.jar -------------------------------------------------------------------------------- /lib/spring-expression-5.3.0-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/spring-expression-5.3.0-sources.jar -------------------------------------------------------------------------------- /lib/spring-expression-5.3.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/spring-expression-5.3.0.jar -------------------------------------------------------------------------------- /lib/spring-jdbc-5.3.0-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/spring-jdbc-5.3.0-sources.jar -------------------------------------------------------------------------------- /lib/spring-jdbc-5.3.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/spring-jdbc-5.3.0.jar -------------------------------------------------------------------------------- /lib/spring-orm-5.3.0-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/spring-orm-5.3.0-sources.jar -------------------------------------------------------------------------------- /lib/spring-orm-5.3.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/spring-orm-5.3.0.jar -------------------------------------------------------------------------------- /lib/spring-tx-5.3.0-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/spring-tx-5.3.0-sources.jar -------------------------------------------------------------------------------- /lib/spring-tx-5.3.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/lib/spring-tx-5.3.0.jar -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch01/Readme.txt: -------------------------------------------------------------------------------- 1 | No code for this package. 2 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/Readme.txt: -------------------------------------------------------------------------------- 1 | This package is about Spring Data JDBC. 2 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/jdbc/basic/JdbcTest.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.jdbc.basic; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import org.javaturk.spring.data.ch02.jdbc.basic.dao.PersonJdbcDAO; 7 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 8 | import org.javaturk.spring.data.ch02.jdbc.common.domain.PersonFactory; 9 | import org.javaturk.spring.data.ch02.jdbc.common.domain.ex.NoSuchPersonException; 10 | 11 | public class JdbcTest { 12 | private static PersonJdbcDAO dao = new PersonJdbcDAO(); 13 | 14 | public static void main(String[] args) throws NoSuchPersonException { 15 | System.out.println("Number of person: " + dao.retrievePersonCount()); 16 | 17 | // int id = 2; 18 | // Person person2 = new Person(id, "Ali", "Ozmen", new Date()); 19 | // dao.savePerson(person2); 20 | // 21 | // Person personRetrieved = null; 22 | // try { 23 | // personRetrieved = dao.retrievePerson(id); 24 | // System.out.println(personRetrieved); 25 | // } catch (NoSuchPersonException e) { 26 | // System.out.println("Person does not exists!"); 27 | // System.out.println(e.getMessage()); 28 | // } 29 | 30 | // dao.deletePerson(personRetrieved); 31 | 32 | // savePersons(100); 33 | 34 | // List persons = dao.retrieveAllPersons(); 35 | // for(Person person : persons) 36 | // System.out.println(person); 37 | 38 | // int id = 2; 39 | // Person person = dao.retrievePerson(id); 40 | // System.out.println("Before update: " + person); 41 | // person.setDob(new Date(2000000000)); 42 | // dao.updatePersonDOB(person); 43 | // person = dao.retrievePerson(id); 44 | // System.out.println("After update: " + person); 45 | 46 | // dao.deleteAllPersons(); 47 | } 48 | 49 | /** 50 | * Utility method to populate the database 51 | * 52 | * @param n Number of the persons to be created. 53 | */ 54 | public static void savePersons(int n) { 55 | System.out.println("\nSaving " + n + " persons to DB"); 56 | PersonFactory personFactory = PersonFactory.getInstance(); 57 | for (int i = 0; i < n; i++) { 58 | Person p = personFactory.createPerson(); 59 | dao.savePerson(p); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/jdbc/basic/dao/PersonJdbcDAO.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.jdbc.basic.dao; 2 | 3 | import java.sql.Connection; 4 | import java.sql.PreparedStatement; 5 | import java.sql.ResultSet; 6 | import java.sql.SQLException; 7 | import java.util.ArrayList; 8 | import java.util.Date; 9 | import java.util.List; 10 | 11 | import org.javaturk.spring.data.ch02.jdbc.basic.util.JdbcUtil; 12 | import org.javaturk.spring.data.ch02.jdbc.common.data.PersonDAO; 13 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 14 | import org.javaturk.spring.data.ch02.jdbc.common.domain.PersonFactory; 15 | import org.javaturk.spring.data.ch02.jdbc.common.domain.ex.NoSuchPersonException; 16 | 17 | public class PersonJdbcDAO implements PersonDAO { 18 | private static final String SAVE_PERSON_QUERY = "INSERT INTO PERSONS VALUES(?,?,?,?)"; 19 | private static final String COUNT_QUERY = "SELECT COUNT(*) AS COUNT FROM PERSONS"; 20 | private static final String RETRIEVE_PERSON_QUERY = "SELECT * FROM PERSONS WHERE ID = ?"; 21 | private static final String RETRIEVE_ALL_PERSONS_QUERY = "SELECT * FROM PERSONS"; 22 | private static final String UPDATE_PERSONDOB_QUERY = "UPDATE PERSONS SET DATEOFBIRTH = ? WHERE ID = ?"; 23 | private static final String DELETE_PERSON_QUERY = "DELETE FROM PERSONS WHERE ID = ?"; 24 | private static final String DELETE_ALL_PERSONS_QUERY = "DELETE FROM PERSONS"; 25 | 26 | @Override 27 | public void savePerson(Person person) { 28 | System.out.println("\nSaving person:" + person); 29 | Connection conn = getConnection(); 30 | PreparedStatement stmt = null; 31 | try { 32 | stmt = conn.prepareStatement(SAVE_PERSON_QUERY); 33 | stmt.setInt(1, person.getId()); 34 | stmt.setString(2, person.getFirstName()); 35 | stmt.setString(3, person.getLastName()); 36 | stmt.setDate(4, person.getDobAsSQlDate()); 37 | int updateCount = stmt.executeUpdate(); 38 | if (updateCount != 1) 39 | System.out.println("Problem with saving the person."); 40 | else 41 | System.out.println("Person saved!"); 42 | } catch (SQLException e) { 43 | System.out.println("Problem with statement: " + e.getMessage()); 44 | e.printStackTrace(); 45 | } finally { 46 | returnConnection(conn); 47 | } 48 | } 49 | 50 | @Override 51 | public int retrievePersonCount() { 52 | int personCount = -1; 53 | Connection conn = getConnection(); 54 | try { 55 | PreparedStatement stmt = conn.prepareStatement(COUNT_QUERY); 56 | ResultSet rs = stmt.executeQuery(); 57 | while(rs.next()){ 58 | personCount = rs.getInt("COUNT"); 59 | } 60 | } catch (SQLException e) { 61 | System.out.println("Problem with statement: " + e.getMessage()); 62 | e.printStackTrace(); 63 | } 64 | finally{ 65 | returnConnection(conn); 66 | } 67 | return personCount; 68 | } 69 | 70 | @Override 71 | public Person retrievePerson(int id) throws NoSuchPersonException { 72 | System.out.println("\nRetrieving the person with id = " + id); 73 | Person personRetrieved = null; 74 | Connection conn = getConnection(); 75 | try { 76 | PreparedStatement stmt = conn.prepareStatement(RETRIEVE_PERSON_QUERY); 77 | stmt.setInt(1, id); 78 | ResultSet rs = stmt.executeQuery(); 79 | while(rs.next()){ 80 | String firstName = rs.getString("FIRSTNAME"); 81 | String lastName = rs.getString("LASTNAME"); 82 | Date dob = rs.getDate("DATEOFBIRTH"); 83 | personRetrieved = new Person(id, firstName, lastName, dob); 84 | } 85 | if(personRetrieved == null) 86 | // System.out.println("No such person with id = " + id); 87 | throw new NoSuchPersonException(id); 88 | } catch (SQLException e) { 89 | System.out.println("Problem with statement: " + e.getMessage()); 90 | e.printStackTrace(); 91 | } 92 | finally{ 93 | returnConnection(conn); 94 | } 95 | return personRetrieved; 96 | } 97 | 98 | @Override 99 | public List retrieveAllPersons() { 100 | System.out.println("\nRetrieving all of the persons."); 101 | List persons = new ArrayList(); 102 | Connection conn = getConnection(); 103 | try { 104 | PreparedStatement stmt = conn.prepareStatement(RETRIEVE_ALL_PERSONS_QUERY); 105 | ResultSet rs = stmt.executeQuery(); 106 | while (rs.next()) { 107 | int id = rs.getInt("ID"); 108 | String firstName = rs.getString("FIRSTNAME"); 109 | String lastName = rs.getString("LASTNAME"); 110 | Date dob = rs.getDate("DATEOFBIRTH"); 111 | Person personRetrieved = new Person(id, firstName, lastName, dob); 112 | persons.add(personRetrieved); 113 | } 114 | } catch (SQLException e) { 115 | System.out.println("Problem with statement: " + e.getMessage()); 116 | e.printStackTrace(); 117 | } finally { 118 | returnConnection(conn); 119 | } 120 | System.out.println(persons.size() + " persons retrieved."); 121 | return persons; 122 | } 123 | 124 | @Override 125 | public void updatePersonDOB(Person person) { 126 | System.out.println("\nUpdating a person's date of birth:" + person); 127 | Connection conn = getConnection(); 128 | PreparedStatement stmt = null; 129 | try { 130 | stmt = conn.prepareStatement(UPDATE_PERSONDOB_QUERY); 131 | stmt.setDate(1, person.getDobAsSQlDate()); 132 | stmt.setInt(2, person.getId()); 133 | int updateCount = stmt.executeUpdate(); 134 | if (updateCount != 1) { 135 | System.out.println("No such person with id = " + person.getId()); 136 | System.out.println("No person updated!"); 137 | } else 138 | System.out.println("Person updated!"); 139 | } catch (SQLException e) { 140 | System.out.println("Problem with statement: " + e.getMessage()); 141 | e.printStackTrace(); 142 | } finally { 143 | returnConnection(conn); 144 | } 145 | } 146 | 147 | @Override 148 | public void deletePerson(Person person) { 149 | System.out.println("\nDeleting a person:" + person); 150 | Connection conn = getConnection(); 151 | try { 152 | PreparedStatement stmt = conn.prepareStatement(DELETE_PERSON_QUERY); 153 | stmt.setInt(1, person.getId()); 154 | int updateCount = stmt.executeUpdate(); 155 | if (updateCount != 1) { 156 | System.out.println("No such person with id = " + person.getId()); 157 | System.out.println("No person deleted!."); 158 | } else 159 | System.out.println("Person deleted!"); 160 | } catch (SQLException e) { 161 | System.out.println("Problem with statement: " + e.getMessage()); 162 | e.printStackTrace(); 163 | } finally { 164 | returnConnection(conn); 165 | } 166 | } 167 | 168 | @Override 169 | public void deleteAllPersons() { 170 | System.out.println("\nDeleting all persons."); 171 | Connection conn = getConnection(); 172 | try { 173 | PreparedStatement stmt = conn.prepareStatement(DELETE_ALL_PERSONS_QUERY); 174 | int updateCount = stmt.executeUpdate(); 175 | System.out.println(updateCount + " persons deleted!"); 176 | } catch (SQLException e) { 177 | System.out.println("Problem with statement: " + e.getMessage()); 178 | e.printStackTrace(); 179 | } finally { 180 | returnConnection(conn); 181 | } 182 | } 183 | 184 | private Connection getConnection() { 185 | return JdbcUtil.getConnection(); 186 | } 187 | 188 | private void returnConnection(Connection conn) { 189 | try { 190 | // Closing connection would close statements too. 191 | conn.close(); 192 | } catch (SQLException e) { 193 | System.out.println("Problem with closing the connection: " + e.getMessage()); 194 | e.printStackTrace(); 195 | } 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/jdbc/basic/uml/CD1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/src/org/javaturk/spring/data/ch02/jdbc/basic/uml/CD1.png -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/jdbc/basic/uml/CD2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/src/org/javaturk/spring/data/ch02/jdbc/basic/uml/CD2.png -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/jdbc/basic/util/JdbcUtil.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.jdbc.basic.util; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.io.FileReader; 5 | import java.io.IOException; 6 | import java.sql.Connection; 7 | import java.sql.DriverManager; 8 | import java.sql.SQLException; 9 | import java.util.Properties; 10 | 11 | import javax.sql.DataSource; 12 | 13 | import org.apache.commons.dbcp2.BasicDataSource; 14 | import org.springframework.context.annotation.Bean; 15 | 16 | public class JdbcUtil { 17 | private static Properties settings = new Properties(); 18 | private static String fileName = "/Users/akin/Java/Eclipse/202003/workspace/Spring WS/Spring Data/src/org/javaturk/spring/data/ch02/jdbc/common/resources/jdbc.properties"; 19 | 20 | private static String url; 21 | private static String ip; 22 | private static String port; 23 | private static String username; 24 | private static String password; 25 | private static String driver; 26 | 27 | private static BasicDataSource basicDataSource; 28 | 29 | static { 30 | FileReader in = null; 31 | try { 32 | in = new FileReader(fileName); 33 | } catch (FileNotFoundException e1) { 34 | System.out.println("File is not found: " + fileName); 35 | e1.printStackTrace(); 36 | } 37 | try { 38 | settings.load(in); 39 | } catch (IOException e) { 40 | System.out.println("Problem with IO: " + e.getMessage()); 41 | e.printStackTrace(); 42 | } 43 | 44 | // Use this line to list all loaded properties. 45 | // settings.list(System.out); 46 | 47 | url = settings.getProperty("url"); 48 | username = settings.getProperty("username"); 49 | password = settings.getProperty("password"); 50 | driver = settings.getProperty("driver"); 51 | 52 | listProperties(); 53 | 54 | // Create a data source 55 | basicDataSource = new BasicDataSource(); 56 | basicDataSource.setDriverClassName(driver); 57 | basicDataSource.setUrl(url); 58 | basicDataSource.setUsername(username); 59 | basicDataSource.setPassword(password); 60 | } 61 | 62 | // public static Connection getConnection() { 63 | // Connection connection = null; 64 | // try { 65 | // Class.forName(driver); 66 | // connection = DriverManager.getConnection(url, username, password); 67 | // } catch (ClassNotFoundException e) { 68 | // System.out.println(driver + " is not found: " + e.getMessage()); 69 | // e.printStackTrace(); 70 | // } catch (SQLException e) { 71 | // System.out.println("In JDBCUtil, problem with getting a connection: " + e.getMessage()); 72 | // e.printStackTrace(); 73 | // } 74 | // return connection; 75 | // } 76 | 77 | public static Connection getConnection() { 78 | Connection connection = null; 79 | try { 80 | connection = basicDataSource.getConnection(); 81 | } catch (SQLException e) { 82 | System.out.println("In JDBCUtil, problem with getting a connection: " + e.getMessage()); 83 | e.printStackTrace(); 84 | } 85 | return connection; 86 | } 87 | 88 | public static void listProperties() { 89 | System.err.format("\n******************************************************************************\n"); 90 | System.err.format("* %50s %25s \n", "Creating the connection with following properties", "*"); 91 | System.err.format("* %-20s %-50s %4s \n", "URL:", url, "*"); 92 | System.err.format("* %-20s %-50s %4s \n", "Username:", username, "*"); 93 | System.err.format("* %-20s %-50s %4s \n", "Password:", password, "*"); 94 | System.err.format("* %-20s %-50s %4s \n", "Driver:", driver, "*"); 95 | System.err.format("******************************************************************************\n"); 96 | System.out.println(); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/jdbc/common/data/PersonDAO.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.jdbc.common.data; 2 | 3 | import java.util.List; 4 | 5 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 6 | import org.javaturk.spring.data.ch02.jdbc.common.domain.ex.NoSuchPersonException; 7 | 8 | public interface PersonDAO { 9 | 10 | public void savePerson(Person person); 11 | 12 | public int retrievePersonCount(); 13 | 14 | public Person retrievePerson(int id) throws NoSuchPersonException; 15 | 16 | public List retrieveAllPersons(); 17 | 18 | public void updatePersonDOB(Person person); 19 | 20 | public void deletePerson(Person person); 21 | 22 | public void deleteAllPersons(); 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/jdbc/common/domain/Factory.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.jdbc.common.domain; 2 | 3 | public interface Factory { 4 | 5 | public Person createPerson(); 6 | } 7 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/jdbc/common/domain/Person.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.jdbc.common.domain; 2 | 3 | import java.util.Date; 4 | 5 | public class Person { 6 | private int id; 7 | private String firstName; 8 | private String lastName; 9 | private Date dob; 10 | 11 | public Person() { 12 | } 13 | 14 | public Person(String firstName, String lastName) { 15 | this(0, firstName, lastName, null); 16 | } 17 | 18 | public Person(int id, String firstName, String lastName, Date dob) { 19 | this.id = id; 20 | this.firstName = firstName; 21 | this.lastName = lastName; 22 | this.dob = dob; 23 | } 24 | 25 | public Person(int id, String firstName, String lastName) { 26 | this(id, firstName, lastName, null); 27 | } 28 | 29 | public Person(int id) { 30 | this(id, null, null, null); 31 | } 32 | 33 | public int getId() { 34 | return id; 35 | } 36 | 37 | public void setId(int id) { 38 | this.id = id; 39 | } 40 | 41 | public String getFirstName() { 42 | return firstName; 43 | } 44 | 45 | public void setFirstName(String firstName) { 46 | this.firstName = firstName; 47 | } 48 | 49 | public String getLastName() { 50 | return lastName; 51 | } 52 | 53 | public void setLastName(String lastName) { 54 | this.lastName = lastName; 55 | } 56 | 57 | public Date getDob() { 58 | return dob; 59 | } 60 | 61 | public void setDob(Date dob) { 62 | this.dob = dob; 63 | } 64 | 65 | public java.sql.Date getDobAsSQlDate() { 66 | return new java.sql.Date(dob.getTime()); 67 | } 68 | 69 | @Override 70 | public int hashCode() { 71 | final int prime = 31; 72 | int result = 1; 73 | result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); 74 | result = prime * result + id; 75 | result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); 76 | return result; 77 | } 78 | 79 | @Override 80 | public boolean equals(Object obj) { 81 | if (this == obj) 82 | return true; 83 | if (obj == null) 84 | return false; 85 | if (getClass() != obj.getClass()) 86 | return false; 87 | Person other = (Person) obj; 88 | if (firstName == null) { 89 | if (other.firstName != null) 90 | return false; 91 | } else if (!firstName.equals(other.firstName)) 92 | return false; 93 | if (id != other.id) 94 | return false; 95 | if (lastName == null) { 96 | if (other.lastName != null) 97 | return false; 98 | } else if (!lastName.equals(other.lastName)) 99 | return false; 100 | return true; 101 | } 102 | 103 | @Override 104 | public String toString() { 105 | return "Person [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + "]"; 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/jdbc/common/domain/PersonFactory.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.jdbc.common.domain; 2 | 3 | import java.util.Calendar; 4 | import java.util.Date; 5 | import java.util.Random; 6 | 7 | public class PersonFactory implements Factory{ 8 | private static PersonFactory personFactory = new PersonFactory(); 9 | private static Random random = new Random(); 10 | 11 | private static String[] firstnames = { "Ali", "Ayse", "Bahar", "Cem", "Demet", "Eylem", "Faruk", "Fatma", "Ganime", 12 | "Haydar", "Halil", "Ismail", "Jale", "Kemal", "Leman", "Mustafa", "Nedim", "Nilufer", "Selim", "Selman", 13 | "Sevda", "Tarik", "Teoman", "Yeliz", "Zuhal" }; 14 | private static String[] lastnames = { "Arabaci", "Aslan", "Batur", "Bulut", "Ceviz", "Karli", "Lale", "Ozturk", 15 | "Pasa", "Sari", "Serim", "Telli", "Torbaci", "Yazar", "Zafer" }; 16 | 17 | private PersonFactory() {} 18 | 19 | public static PersonFactory getInstance() { 20 | return personFactory; 21 | } 22 | 23 | @Override 24 | public Person createPerson() { 25 | Person person = new Person(); 26 | person.setId(createId()); 27 | person.setFirstName(createFirstName()); 28 | person.setLastName(createLastName()); 29 | person.setDob(createDob()); 30 | return person; 31 | } 32 | 33 | private int createId() { 34 | int randomInt = random.nextInt(); 35 | if (randomInt < 0) 36 | randomInt = -randomInt; 37 | return randomInt; 38 | } 39 | 40 | private String createFirstName() { 41 | int randomInt = random.nextInt(25); 42 | return firstnames[randomInt]; 43 | } 44 | 45 | private String createLastName() { 46 | int randomInt = random.nextInt(15); 47 | return lastnames[randomInt]; 48 | } 49 | 50 | private Date createDob() { 51 | Calendar calendar = Calendar.getInstance(); 52 | calendar.set(1950 + random.nextInt(60), random.nextInt(11), random.nextInt(30)); 53 | return calendar.getTime(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/jdbc/common/domain/ex/NoSuchPersonException.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.jdbc.common.domain.ex; 2 | 3 | public class NoSuchPersonException extends Exception{ 4 | private static String message = "No such person found! Id: "; 5 | 6 | public NoSuchPersonException(int id) { 7 | super(message + id); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/jdbc/common/resources/DB.sql: -------------------------------------------------------------------------------- 1 | Derby DB (java DB) 2 | 3 | Create a DB called JPA on Derby with following URL: jdbc:derby://localhost:1527/JPA;create=true 4 | Username is "app" and password is "password" 5 | 6 | MySQL 7 | 8 | Create a DB called JPA on Derby with following URL: jdbc:mysql://localhost/JPA 9 | Username is "root" and password is "password" 10 | 11 | 12 | drop table PERSONS 13 | 14 | PERSONS(ID, FIRSTNAME, LASTNAME, DATEOFBIRTH) 15 | 16 | CREATE TABLE PERSONS( 17 | ID INT PRIMARY KEY, 18 | FIRSTNAME VARCHAR(30) NOT NULL, 19 | LASTNAME VARCHAR(50) NOT NULL, 20 | DATEOFBIRTH DATE 21 | ) 22 | 23 | INSERT INTO PERSONS VALUES(1, 'Mihrimah', 'Kaldiroglu', {d '2004-08-24'}) 24 | 25 | SELECT * FROM PERSONS 26 | 27 | SELECT COUNT(*) FROM PERSONS 28 | 29 | Select * from PERSONS Where lastname = 'Kaldiroglu' 30 | 31 | 32 | 33 | 34 | **************************************** 35 | Drop Table PERSON_ENTITY 36 | 37 | 38 | 39 | Drop Table PERSON_EM 40 | Drop Table CAR_EM 41 | 42 | Drop Table PERSON_TX 43 | 44 | 45 | 46 | **************************************** 47 | 48 | Drop Table CAR_EM 49 | 50 | Drop Table EmployeeTemporal; 51 | 52 | Drop Table CONSULTANTST 53 | Drop Table CONSULTANT_INHERATNCE_JOINED 54 | Drop Table CONSULTANT_INHERITANCE_JOINED 55 | 56 | Drop Table DIRECTOR_INHERITANCE_JOINED_TABLE 57 | Drop Table EMPLOYEE_INHERITANCE_JOINED_TABLE; 58 | Drop Table EMPLOYEE_MAPPEDSUPERCLASS 59 | 60 | Drop Table MANAGER_INHERITANCE_JOINED_TABLE 61 | Drop Table PERSON_INHERITANCE_A_SINGLE_TABLE; 62 | Drop Table PERSON_INHERITANCE_JOINED_TABLE; 63 | Drop Table PERSON_INHERITANCE_SINGLE_TABLE; 64 | 65 | Drop Table ManagerInheritanceTPC; 66 | Drop Table EmployeeInheritanceTPC; 67 | Drop Table DirectorInheritanceTPC 68 | Drop Table ConsultantInheritanceTPC 69 | Drop Table PersonInheritanceTPC; 70 | 71 | Drop Table PERSONS 72 | 73 | Drop Table PERSON_EM; 74 | Drop Table PERSON_ENTITY; 75 | Drop Table PERSONENTITY; 76 | Drop Table PERSON_IDENTITY_ASSIGNED; 77 | Drop Table PERSON_IDENTITY_AUTO; 78 | Drop Table IDGeneratorTable; 79 | Drop Table PersonIdentityComposite1; 80 | Drop Table PersonIdentityComposite2; 81 | Drop Table PersonIdentityIdentity; 82 | Drop Table PersonIdentityTable 83 | 84 | Drop Table PERSONTX 85 | 86 | Drop Table PersonCarListenerBi; 87 | Drop Table PersonListener; 88 | Drop Table CarListener; 89 | 90 | Drop Table PersonLob 91 | Drop Table SEQUENCE 92 | drop Table StudentIdentityTable 93 | 94 | Drop Table PersonOne2OneBidir 95 | Drop Table PersonOne2ManyBidir 96 | 97 | Drop Table PersonLocking 98 | Drop Table Sequence 99 | Drop Table Hibernate_Sequence 100 | 101 | Drop Table Person_em 102 | 103 | Drop Table PersonOne2OneBidir 104 | Drop Table PersonOne2ManyBidir 105 | 106 | Drop Table MANAGER_INHERITANCE_JOINED_TABLE 107 | Drop Table EMPLOYEE_INHERITANCE_JOINED_TABLE 108 | Drop Table PERSON_INHERITANCE_JOINED_TABLE 109 | Drop Table PERSON_INHERITANCE_SINGLE_TABLE 110 | 111 | Drop Table CarOne2ManyBiDir; 112 | Drop Table CarOne2OneBiDir; 113 | 114 | Drop Table PersonCarMany2ManyBi; 115 | Drop Table PersonMany2ManyBiDir; 116 | Drop Table CarMany2ManyBiDir; 117 | 118 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/jdbc/common/resources/jdbc.properties: -------------------------------------------------------------------------------- 1 | #JDBC Properties 2 | #Please activate the suitable set of properties of your DB choice. 3 | 4 | #Oracle XE 5 | #url=jdbc:oracle:thin:@localhost:1521:XE 6 | #username=coffee 7 | #password=password 8 | #driver=oracle.jdbc.driver.OracleDriver 9 | 10 | #JavaDB (Derby) 11 | #url=jdbc:derby://localhost:1527/JPA;create=true 12 | #username=app 13 | #password=password 14 | #driver=org.apache.derby.jdbc.ClientDriver 15 | 16 | 17 | #MySQL 18 | url:jdbc:mysql://localhost/JDBC 19 | username=root 20 | password=password 21 | driver=com.mysql.cj.jdbc.Driver 22 | 23 | 24 | #url:jdbc:postgresql://localhost:5432/JDBC 25 | #username=postgres 26 | #password=password 27 | #driver=org.postgresql.Driver 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/jdbc/spring/SpringTest.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.jdbc.spring; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import org.javaturk.spring.data.ch02.jdbc.common.data.PersonDAO; 7 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Factory; 8 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 9 | import org.javaturk.spring.data.ch02.jdbc.common.domain.PersonFactory; 10 | import org.javaturk.spring.data.ch02.jdbc.common.domain.ex.NoSuchPersonException; 11 | import org.javaturk.spring.data.ch02.jdbc.spring.conf.AppConfig; 12 | import org.javaturk.spring.data.ch02.jdbc.spring.conf.JDBCConfig; 13 | import org.javaturk.spring.data.ch02.jdbc.spring.dao.PersonJdbcConnectionDAO; 14 | import org.javaturk.spring.data.ch02.jdbc.spring.dao.PersonJdbcDataSourceDAO; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.beans.factory.annotation.Qualifier; 17 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 18 | import org.springframework.context.annotation.Import; 19 | 20 | @Import({AppConfig.class, JDBCConfig.class}) 21 | public class SpringTest { 22 | 23 | // @Autowired 24 | // @Qualifier("personJdbcConnectionDAO") 25 | // PersonDAO dao; 26 | 27 | @Autowired 28 | @Qualifier("personJdbcDataSourceDAO") 29 | PersonDAO dao; 30 | 31 | @Autowired 32 | Factory personFactory; 33 | 34 | public static void main(String[] args) { 35 | AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringTest.class); 36 | SpringTest test = context.getBean(SpringTest.class); 37 | // That's a very naive code that I still keep doing! :) 38 | // SpringTest test = new SpringTest(); 39 | test.run(); 40 | } 41 | 42 | public void run() { 43 | System.out.println("Number of person: " + dao.retrievePersonCount()); 44 | 45 | int id = 1; 46 | // Person person2 = new Person(id, "Ali", "Ozmen", new Date()); 47 | // dao.savePerson(person2); 48 | 49 | // Person personRetrieved = null; 50 | // try { 51 | // personRetrieved = dao.retrievePerson(id); 52 | // System.out.println(personRetrieved); 53 | // } catch (NoSuchPersonException e) { 54 | // System.out.println("Person does not exists!"); 55 | // System.out.println(e.getMessage()); 56 | // } 57 | 58 | // dao.deletePerson(personRetrieved); 59 | 60 | // savePersons(100); 61 | List persons = dao.retrieveAllPersons(); 62 | for(Person person : persons) 63 | System.out.println(person); 64 | 65 | // int id = 5; 66 | // Person person = dao.retrievePerson(id); 67 | // System.out.println("Before update: " + person); 68 | // person.setDob(new Date(2000000000)); 69 | // dao.updatePersonDOB(person); 70 | // person = dao.retrievePerson(id); 71 | // System.out.println("After update: " + person); 72 | 73 | // dao.deleteAllPersons(); 74 | } 75 | 76 | /** 77 | * Utility method to populate the database 78 | * 79 | * @param n Number of the persons to be created. 80 | */ 81 | public void savePersons(int n) { 82 | System.out.println("\nSaving " + n + " persons to DB"); 83 | for (int i = 0; i < n; i++) { 84 | Person p = personFactory.createPerson(); 85 | dao.savePerson(p); 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/jdbc/spring/conf/AppConfig.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.jdbc.spring.conf; 2 | 3 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Factory; 4 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 5 | import org.javaturk.spring.data.ch02.jdbc.common.domain.PersonFactory; 6 | import org.javaturk.spring.data.ch02.jdbc.spring.dao.PersonJdbcConnectionDAO; 7 | import org.javaturk.spring.data.ch02.jdbc.spring.dao.PersonJdbcDataSourceDAO; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.beans.factory.annotation.Qualifier; 10 | import org.springframework.context.annotation.Bean; 11 | import org.springframework.context.annotation.Configuration; 12 | import org.springframework.context.annotation.Scope; 13 | 14 | @Configuration 15 | public class AppConfig { 16 | 17 | @Autowired 18 | private Factory personFactory; 19 | 20 | @Bean 21 | @Scope("prototype") 22 | public Person person() { 23 | return personFactory.createPerson(); 24 | } 25 | 26 | @Bean 27 | @Scope("singleton") 28 | public PersonFactory personFactory() { 29 | return PersonFactory.getInstance(); 30 | } 31 | 32 | @Bean 33 | @Qualifier("personJdbcConnectionDAO") 34 | @Scope("prototype") 35 | public PersonJdbcConnectionDAO personJdbcConnectionDAO() { 36 | System.out.println("Creating personJdbcConnectionDAO"); 37 | return new PersonJdbcConnectionDAO(); 38 | } 39 | 40 | @Bean 41 | @Qualifier("personJdbcDataSourceDAO") 42 | @Scope("prototype") 43 | public PersonJdbcDataSourceDAO personJdbcDataSourceDAO() { 44 | System.out.println("Creating personJdbcDataSourceDAO"); 45 | return new PersonJdbcDataSourceDAO(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/jdbc/spring/conf/JDBCConfig.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.jdbc.spring.conf; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.SQLException; 6 | 7 | import javax.annotation.PostConstruct; 8 | import javax.sql.DataSource; 9 | 10 | import org.apache.commons.dbcp2.BasicDataSource; 11 | import org.springframework.beans.factory.annotation.Value; 12 | import org.springframework.context.annotation.Bean; 13 | import org.springframework.context.annotation.Configuration; 14 | import org.springframework.context.annotation.PropertySource; 15 | import org.springframework.context.annotation.Scope; 16 | 17 | @Configuration 18 | @PropertySource("org/javaturk/spring/data/ch02/jdbc/common/resources/jdbc.properties") 19 | public class JDBCConfig { 20 | 21 | @Value("${url}") 22 | private String url; 23 | 24 | @Value("${username}") 25 | private String username; 26 | 27 | @Value("${password}") 28 | private String password; 29 | 30 | @Value("${driver}") 31 | private String driver; 32 | 33 | private BasicDataSource basicDataSource; 34 | 35 | @Bean 36 | public DataSource dataSource() { 37 | basicDataSource = new BasicDataSource(); 38 | basicDataSource.setDriverClassName(driver); 39 | basicDataSource.setUrl(url); 40 | basicDataSource.setUsername(username); 41 | basicDataSource.setPassword(password); 42 | return basicDataSource; 43 | } 44 | 45 | @Bean 46 | @Scope("prototype") 47 | public Connection connection() { 48 | Connection connection = null; 49 | try { 50 | Class.forName(driver); 51 | connection = DriverManager.getConnection(url, username, password); 52 | } catch (ClassNotFoundException e) { 53 | System.out.println(driver + " is not found: " + e.getMessage()); 54 | e.printStackTrace(); 55 | } catch (SQLException e) { 56 | System.out.println("In JDBCConfig, problem with getting a connection: " + e.getMessage()); 57 | e.printStackTrace(); 58 | } 59 | return connection; 60 | } 61 | 62 | @PostConstruct 63 | public void listProperties() { 64 | System.err.format("\n******************************************************************************\n"); 65 | System.err.format("* %50s %25s \n", "Creating the connection with following properties", "*"); 66 | System.err.format("* %-20s %-50s %4s \n", "URL:", url, "*"); 67 | System.err.format("* %-20s %-50s %4s \n", "Username:", username, "*"); 68 | System.err.format("* %-20s %-50s %4s \n", "Password:", password, "*"); 69 | System.err.format("* %-20s %-50s %4s \n", "Driver:", driver, "*"); 70 | System.err.format("******************************************************************************\n"); 71 | System.out.println(); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/jdbc/spring/dao/PersonJdbcConnectionDAO.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.jdbc.spring.dao; 2 | 3 | import java.sql.Connection; 4 | import java.sql.PreparedStatement; 5 | import java.sql.ResultSet; 6 | import java.sql.SQLException; 7 | import java.util.ArrayList; 8 | import java.util.Date; 9 | import java.util.List; 10 | 11 | import javax.sql.DataSource; 12 | 13 | import org.javaturk.spring.data.ch02.jdbc.common.data.PersonDAO; 14 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 15 | import org.javaturk.spring.data.ch02.jdbc.common.domain.ex.NoSuchPersonException; 16 | import org.springframework.beans.BeansException; 17 | import org.springframework.beans.factory.BeanFactory; 18 | import org.springframework.beans.factory.BeanFactoryAware; 19 | import org.springframework.beans.factory.annotation.Autowired; 20 | 21 | public class PersonJdbcConnectionDAO implements PersonDAO, BeanFactoryAware { 22 | private static final String SAVE_PERSON_QUERY = "INSERT INTO PERSONS VALUES(?,?,?,?)"; 23 | private static final String COUNT_QUERY = "SELECT COUNT(*) FROM PERSONS"; 24 | private static final String RETRIEVE_PERSON_QUERY = "SELECT * FROM PERSONS WHERE ID = ?"; 25 | private static final String RETRIEVE_ALL_PERSONS_QUERY = "SELECT * FROM PERSONS"; 26 | private static final String UPDATE_PERSONDOB_QUERY = "UPDATE PERSONS SET DATEOFBIRTH = ? WHERE ID = ?"; 27 | private static final String DELETE_PERSON_QUERY = "DELETE FROM PERSONS WHERE ID = ?"; 28 | private static final String DELETE_ALL_PERSONS_QUERY = "DELETE FROM PERSONS"; 29 | 30 | // Don't do that. It needs to be refreshed every time a connection is needed 31 | // because of the fact that 32 | // connection object is closed after it is used. 33 | // @Autowired 34 | // private Connection conn; 35 | 36 | private BeanFactory factory; 37 | 38 | @Override 39 | public void savePerson(Person person) { 40 | System.out.println("\nSaving person:" + person); 41 | Connection conn = getConnection(); 42 | PreparedStatement stmt = null; 43 | try { 44 | stmt = conn.prepareStatement(SAVE_PERSON_QUERY); 45 | stmt.setInt(1, person.getId()); 46 | stmt.setString(2, person.getFirstName()); 47 | stmt.setString(3, person.getLastName()); 48 | stmt.setDate(4, person.getDobAsSQlDate()); 49 | int updateCount = stmt.executeUpdate(); 50 | if (updateCount != 1) 51 | System.out.println("Problem with saving the person."); 52 | else 53 | System.out.println("Person saved!"); 54 | } catch (SQLException e) { 55 | System.out.println("Problem with statement: " + e.getMessage()); 56 | e.printStackTrace(); 57 | } finally { 58 | returnConnection(conn); 59 | } 60 | } 61 | 62 | @Override 63 | public int retrievePersonCount() { 64 | int personCount = -1; 65 | Connection conn = getConnection(); 66 | try { 67 | PreparedStatement stmt = conn.prepareStatement(COUNT_QUERY); 68 | ResultSet rs = stmt.executeQuery(); 69 | while(rs.next()){ 70 | personCount = rs.getInt("COUNT"); 71 | } 72 | } catch (SQLException e) { 73 | System.out.println("Problem with statement: " + e.getMessage()); 74 | e.printStackTrace(); 75 | } 76 | finally{ 77 | returnConnection(conn); 78 | } 79 | return personCount; 80 | } 81 | 82 | @Override 83 | public Person retrievePerson(int id) throws NoSuchPersonException { 84 | System.out.println("\nRetrieving the person with id = " + id); 85 | Person personRetrieved = null; 86 | Connection conn = getConnection(); 87 | try { 88 | PreparedStatement stmt = conn.prepareStatement(RETRIEVE_PERSON_QUERY); 89 | stmt.setInt(1, id); 90 | ResultSet rs = stmt.executeQuery(); 91 | while (rs.next()) { 92 | String firstName = rs.getString("FIRSTNAME"); 93 | String lastName = rs.getString("LASTNAME"); 94 | Date dob = rs.getDate("DATEOFBIRTH"); 95 | personRetrieved = new Person(id, firstName, lastName, dob); 96 | } 97 | if (personRetrieved == null) 98 | // System.out.println("No such person with id = " + id); 99 | throw new NoSuchPersonException(id); 100 | } catch (SQLException e) { 101 | System.out.println("Problem with statement: " + e.getMessage()); 102 | e.printStackTrace(); 103 | } finally { 104 | returnConnection(conn); 105 | } 106 | return personRetrieved; 107 | } 108 | 109 | @Override 110 | public List retrieveAllPersons() { 111 | System.out.println("\nRetrieving all of the persons."); 112 | List persons = new ArrayList(); 113 | Connection conn = getConnection(); 114 | try { 115 | PreparedStatement stmt = conn.prepareStatement(RETRIEVE_ALL_PERSONS_QUERY); 116 | ResultSet rs = stmt.executeQuery(); 117 | while (rs.next()) { 118 | int id = rs.getInt("ID"); 119 | String firstName = rs.getString("FIRSTNAME"); 120 | String lastName = rs.getString("LASTNAME"); 121 | Date dob = rs.getDate("DATEOFBIRTH"); 122 | Person personRetrieved = new Person(id, firstName, lastName, dob); 123 | persons.add(personRetrieved); 124 | } 125 | } catch (SQLException e) { 126 | System.out.println("Problem with statement: " + e.getMessage()); 127 | e.printStackTrace(); 128 | } finally { 129 | returnConnection(conn); 130 | } 131 | System.out.println(persons.size() + " persons retrieved."); 132 | return persons; 133 | } 134 | 135 | @Override 136 | public void updatePersonDOB(Person person) { 137 | System.out.println("\nUpdating a person's date of birth:" + person); 138 | Connection conn = getConnection(); 139 | PreparedStatement stmt = null; 140 | try { 141 | stmt = conn.prepareStatement(UPDATE_PERSONDOB_QUERY); 142 | stmt.setDate(1, person.getDobAsSQlDate()); 143 | stmt.setInt(2, person.getId()); 144 | int updateCount = stmt.executeUpdate(); 145 | if (updateCount != 1) { 146 | System.out.println("No such person with id = " + person.getId()); 147 | System.out.println("No person updated!"); 148 | } else 149 | System.out.println("Person updated!"); 150 | } catch (SQLException e) { 151 | System.out.println("Problem with statement: " + e.getMessage()); 152 | e.printStackTrace(); 153 | } finally { 154 | returnConnection(conn); 155 | } 156 | } 157 | 158 | @Override 159 | public void deletePerson(Person person) { 160 | System.out.println("\nDeleting a person:" + person); 161 | Connection conn = getConnection(); 162 | try { 163 | PreparedStatement stmt = conn.prepareStatement(DELETE_PERSON_QUERY); 164 | stmt.setInt(1, person.getId()); 165 | int updateCount = stmt.executeUpdate(); 166 | if (updateCount != 1) { 167 | System.out.println("No such person with id = " + person.getId()); 168 | System.out.println("No person deleted!."); 169 | } else 170 | System.out.println("Person deleted!"); 171 | } catch (SQLException e) { 172 | System.out.println("Problem with statement: " + e.getMessage()); 173 | e.printStackTrace(); 174 | } finally { 175 | returnConnection(conn); 176 | } 177 | } 178 | 179 | @Override 180 | public void deleteAllPersons() { 181 | System.out.println("\nDeleting all persons."); 182 | Connection conn = getConnection(); 183 | try { 184 | PreparedStatement stmt = conn.prepareStatement(DELETE_ALL_PERSONS_QUERY); 185 | int updateCount = stmt.executeUpdate(); 186 | System.out.println(updateCount + " persons deleted!"); 187 | } catch (SQLException e) { 188 | System.out.println("Problem with statement: " + e.getMessage()); 189 | e.printStackTrace(); 190 | } finally { 191 | returnConnection(conn); 192 | } 193 | } 194 | 195 | private Connection getConnection() { 196 | Connection conn = (Connection) factory.getBean("connection"); 197 | return conn; 198 | } 199 | 200 | private void returnConnection(Connection conn) { 201 | try { 202 | conn.close(); 203 | } catch (SQLException e) { 204 | System.out.println("Problem with closing the connection: " + e.getMessage()); 205 | e.printStackTrace(); 206 | } 207 | } 208 | 209 | @Override 210 | public void setBeanFactory(BeanFactory factory) throws BeansException { 211 | this.factory = factory; 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/jdbc/spring/dao/PersonJdbcDataSourceDAO.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.jdbc.spring.dao; 2 | 3 | import java.sql.Connection; 4 | import java.sql.PreparedStatement; 5 | import java.sql.ResultSet; 6 | import java.sql.SQLException; 7 | import java.util.ArrayList; 8 | import java.util.Date; 9 | import java.util.List; 10 | 11 | import javax.sql.DataSource; 12 | 13 | import org.javaturk.spring.data.ch02.jdbc.common.data.PersonDAO; 14 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 15 | import org.javaturk.spring.data.ch02.jdbc.common.domain.ex.NoSuchPersonException; 16 | import org.springframework.beans.BeansException; 17 | import org.springframework.beans.factory.BeanFactory; 18 | import org.springframework.beans.factory.BeanFactoryAware; 19 | import org.springframework.beans.factory.annotation.Autowired; 20 | 21 | public class PersonJdbcDataSourceDAO implements PersonDAO { 22 | private static final String SAVE_PERSON_QUERY = "INSERT INTO PERSONS VALUES(?,?,?,?)"; 23 | private static final String COUNT_QUERY = "SELECT COUNT(*) AS COUNT FROM PERSONS"; 24 | private static final String RETRIEVE_PERSON_QUERY = "SELECT * FROM PERSONS WHERE ID = ?"; 25 | private static final String RETRIEVE_ALL_PERSONS_QUERY = "SELECT * FROM PERSONS"; 26 | private static final String UPDATE_PERSONDOB_QUERY = "UPDATE PERSONS SET DATEOFBIRTH = ? WHERE ID = ?"; 27 | private static final String DELETE_PERSON_QUERY = "DELETE FROM PERSONS WHERE ID = ?"; 28 | private static final String DELETE_ALL_PERSONS_QUERY = "DELETE FROM PERSONS"; 29 | 30 | // Don't do that. It needs to be refreshed every time a connection is needed 31 | // because of the fact that 32 | // connection object is closed after it is used. So DataSource is injected instead. 33 | // @Autowired 34 | // private Connection connection; 35 | 36 | @Autowired 37 | private DataSource dataSource; 38 | 39 | @Override 40 | public void savePerson(Person person) { 41 | System.out.println("\nSaving person:" + person); 42 | Connection conn = getConnection(); 43 | PreparedStatement stmt = null; 44 | try { 45 | stmt = conn.prepareStatement(SAVE_PERSON_QUERY); 46 | stmt.setInt(1, person.getId()); 47 | stmt.setString(2, person.getFirstName()); 48 | stmt.setString(3, person.getLastName()); 49 | stmt.setDate(4, person.getDobAsSQlDate()); 50 | int updateCount = stmt.executeUpdate(); 51 | if (updateCount != 1) 52 | System.out.println("Problem with saving the person."); 53 | else 54 | System.out.println("Person saved!"); 55 | } catch (SQLException e) { 56 | System.out.println("Problem with statement: " + e.getMessage()); 57 | e.printStackTrace(); 58 | } finally { 59 | returnConnection(conn); 60 | } 61 | } 62 | 63 | @Override 64 | public Person retrievePerson(int id) throws NoSuchPersonException { 65 | System.out.println("\nRetrieving the person with id = " + id); 66 | Person personRetrieved = null; 67 | Connection conn = getConnection(); 68 | try { 69 | PreparedStatement stmt = conn.prepareStatement(RETRIEVE_PERSON_QUERY); 70 | stmt.setInt(1, id); 71 | ResultSet rs = stmt.executeQuery(); 72 | while (rs.next()) { 73 | String firstName = rs.getString("FIRSTNAME"); 74 | String lastName = rs.getString("LASTNAME"); 75 | Date dob = rs.getDate("DATEOFBIRTH"); 76 | personRetrieved = new Person(id, firstName, lastName, dob); 77 | } 78 | if (personRetrieved == null) 79 | throw new NoSuchPersonException(id); 80 | } catch (SQLException e) { 81 | System.out.println("Problem with statement: " + e.getMessage()); 82 | e.printStackTrace(); 83 | } finally { 84 | returnConnection(conn); 85 | } 86 | return personRetrieved; 87 | } 88 | 89 | @Override 90 | public int retrievePersonCount() { 91 | int personCount = -1; 92 | Connection conn = getConnection(); 93 | try { 94 | PreparedStatement stmt = conn.prepareStatement(COUNT_QUERY); 95 | ResultSet rs = stmt.executeQuery(); 96 | while(rs.next()){ 97 | personCount = rs.getInt("COUNT"); 98 | } 99 | } catch (SQLException e) { 100 | System.out.println("Problem with statement: " + e.getMessage()); 101 | e.printStackTrace(); 102 | } 103 | finally{ 104 | returnConnection(conn); 105 | } 106 | return personCount; 107 | } 108 | 109 | @Override 110 | public List retrieveAllPersons() { 111 | System.out.println("\nRetrieving all of the persons."); 112 | List persons = new ArrayList(); 113 | Connection conn = getConnection(); 114 | try { 115 | PreparedStatement stmt = conn.prepareStatement(RETRIEVE_ALL_PERSONS_QUERY); 116 | ResultSet rs = stmt.executeQuery(); 117 | while (rs.next()) { 118 | int id = rs.getInt("ID"); 119 | String firstName = rs.getString("FIRSTNAME"); 120 | String lastName = rs.getString("LASTNAME"); 121 | Date dob = rs.getDate("DATEOFBIRTH"); 122 | Person personRetrieved = new Person(id, firstName, lastName, dob); 123 | persons.add(personRetrieved); 124 | } 125 | } catch (SQLException e) { 126 | System.out.println("Problem with statement: " + e.getMessage()); 127 | e.printStackTrace(); 128 | } finally { 129 | returnConnection(conn); 130 | } 131 | System.out.println(persons.size() + " persons retrieved."); 132 | return persons; 133 | } 134 | 135 | @Override 136 | public void updatePersonDOB(Person person) { 137 | System.out.println("\nUpdating a person's date of birth:" + person); 138 | Connection conn = getConnection(); 139 | PreparedStatement stmt = null; 140 | try { 141 | stmt = conn.prepareStatement(UPDATE_PERSONDOB_QUERY); 142 | stmt.setDate(1, person.getDobAsSQlDate()); 143 | stmt.setInt(2, person.getId()); 144 | int updateCount = stmt.executeUpdate(); 145 | if (updateCount != 1) { 146 | System.out.println("No such person with id = " + person.getId()); 147 | System.out.println("No person updated!"); 148 | } else 149 | System.out.println("Person updated!"); 150 | } catch (SQLException e) { 151 | System.out.println("Problem with statement: " + e.getMessage()); 152 | e.printStackTrace(); 153 | } finally { 154 | returnConnection(conn); 155 | } 156 | } 157 | 158 | @Override 159 | public void deletePerson(Person person) { 160 | System.out.println("\nDeleting a person:" + person); 161 | Connection conn = getConnection(); 162 | try { 163 | PreparedStatement stmt = conn.prepareStatement(DELETE_PERSON_QUERY); 164 | stmt.setInt(1, person.getId()); 165 | int updateCount = stmt.executeUpdate(); 166 | if (updateCount != 1) { 167 | System.out.println("No such person with id = " + person.getId()); 168 | System.out.println("No person deleted!."); 169 | } else 170 | System.out.println("Person deleted!"); 171 | } catch (SQLException e) { 172 | System.out.println("Problem with statement: " + e.getMessage()); 173 | e.printStackTrace(); 174 | } finally { 175 | returnConnection(conn); 176 | } 177 | } 178 | 179 | @Override 180 | public void deleteAllPersons() { 181 | System.out.println("\nDeleting all persons."); 182 | Connection conn = getConnection(); 183 | try { 184 | PreparedStatement stmt = conn.prepareStatement(DELETE_ALL_PERSONS_QUERY); 185 | int updateCount = stmt.executeUpdate(); 186 | System.out.println(updateCount + " persons deleted!"); 187 | } catch (SQLException e) { 188 | System.out.println("Problem with statement: " + e.getMessage()); 189 | e.printStackTrace(); 190 | } finally { 191 | returnConnection(conn); 192 | } 193 | } 194 | 195 | private Connection getConnection() { 196 | Connection connection = null; 197 | try { 198 | connection = dataSource.getConnection(); 199 | } catch (SQLException e) { 200 | e.printStackTrace(); 201 | } 202 | return connection; 203 | } 204 | 205 | private void returnConnection(Connection conn) { 206 | try { 207 | conn.close(); 208 | } catch (SQLException e) { 209 | System.out.println("Problem with closing the connection: " + e.getMessage()); 210 | e.printStackTrace(); 211 | } 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/jdbc/spring/uml/CD.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/src/org/javaturk/spring/data/ch02/jdbc/spring/uml/CD.png -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/jdbcTemplate/person/JdbcTemplateTest.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.jdbcTemplate.person; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.conf.AppConfig; 7 | import org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.conf.JDBCConfig; 8 | import org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.dao.PersonJdbcTemplateDAO; 9 | import org.javaturk.spring.data.ch02.jdbc.common.data.PersonDAO; 10 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Factory; 11 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 12 | import org.javaturk.spring.data.ch02.jdbc.common.domain.ex.NoSuchPersonException; 13 | import org.javaturk.spring.data.ch02.jdbc.spring.SpringTest; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.beans.factory.annotation.Qualifier; 16 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 17 | import org.springframework.context.annotation.Import; 18 | 19 | @Import({ AppConfig.class, JDBCConfig.class }) 20 | public class JdbcTemplateTest { 21 | // This should be before personFactory otherwise "Is there an unresolvable circular reference?" 22 | @Autowired 23 | PersonDAO dao; 24 | 25 | @Autowired 26 | Factory personFactory; 27 | 28 | public static void main(String[] args) { 29 | AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(JdbcTemplateTest.class); 30 | JdbcTemplateTest test = context.getBean(JdbcTemplateTest.class); 31 | test.run(); 32 | } 33 | 34 | public void run() { 35 | System.out.println("Number of person: " + dao.retrievePersonCount()); 36 | 37 | int id = 11; 38 | // Person person = new Person(id, "Ali", "Ozmen", new Date()); 39 | // dao.savePerson(person); 40 | 41 | Person personRetrieved = null; 42 | try { 43 | personRetrieved = dao.retrievePerson(id); 44 | System.out.println(personRetrieved); 45 | } catch (NoSuchPersonException e) { 46 | System.out.println("Person does not exists!"); 47 | System.out.println(e.getMessage()); 48 | } 49 | 50 | // dao.deletePerson(personRetrieved); 51 | 52 | // savePersons(100); 53 | 54 | // List persons = dao.retrieveAllPersons(); 55 | // System.out.println("There are " + persons.size() + " persons.\n"); 56 | // for(Person person : persons) 57 | // System.out.println(person); 58 | 59 | // int id = 1; 60 | // Person person = dao.retrievePerson(id); 61 | // System.out.println("Before update: " + person); 62 | // person.setDob(new Date(2000000000)); 63 | // dao.updatePersonDOB(person); 64 | // person = dao.retrievePerson(id); 65 | // System.out.println("After update: " + person); 66 | 67 | // dao.deleteAllPersons(); 68 | } 69 | 70 | /** 71 | * Utility method to populate the database 72 | * 73 | * @param n Number of the persons to be created. 74 | */ 75 | public void savePersons(int n) { 76 | System.out.println("\nSaving " + n + " persons to DB"); 77 | for (int i = 0; i < n; i++) { 78 | Person p = personFactory.createPerson(); 79 | dao.savePerson(p); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/jdbcTemplate/person/callback/PersonPreparedStatementIdAndDobSetter.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.callback; 2 | 3 | import java.sql.PreparedStatement; 4 | import java.sql.SQLException; 5 | 6 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 7 | import org.springframework.jdbc.core.PreparedStatementSetter; 8 | 9 | public class PersonPreparedStatementIdAndDobSetter implements PreparedStatementSetter{ 10 | private Person person; 11 | 12 | public PersonPreparedStatementIdAndDobSetter(Person person) { 13 | this.person = person; 14 | } 15 | 16 | @Override 17 | public void setValues(PreparedStatement ps) throws SQLException { 18 | ps.setDate(1, person.getDobAsSQlDate()); 19 | ps.setInt(2, person.getId()); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/jdbcTemplate/person/callback/PersonPreparedStatementIdSetter.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.callback; 2 | 3 | import java.sql.PreparedStatement; 4 | import java.sql.SQLException; 5 | 6 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 7 | import org.springframework.jdbc.core.PreparedStatementSetter; 8 | 9 | public class PersonPreparedStatementIdSetter implements PreparedStatementSetter{ 10 | private Person person; 11 | 12 | public PersonPreparedStatementIdSetter(Person person) { 13 | this.person = person; 14 | } 15 | 16 | @Override 17 | public void setValues(PreparedStatement ps) throws SQLException { 18 | ps.setInt(1, person.getId()); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/jdbcTemplate/person/callback/PersonPreparedStatementSetter.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.callback; 2 | 3 | import java.sql.PreparedStatement; 4 | import java.sql.SQLException; 5 | 6 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 7 | import org.springframework.jdbc.core.PreparedStatementSetter; 8 | 9 | public class PersonPreparedStatementSetter implements PreparedStatementSetter{ 10 | private Person person; 11 | 12 | public PersonPreparedStatementSetter(Person person) { 13 | this.person = person; 14 | } 15 | 16 | @Override 17 | public void setValues(PreparedStatement ps) throws SQLException { 18 | ps.setInt(1, person.getId()); 19 | ps.setString(2, person.getFirstName()); 20 | ps.setString(3, person.getLastName()); 21 | ps.setDate(4, person.getDobAsSQlDate()); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/jdbcTemplate/person/callback/PersonRowMapper.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.callback; 2 | 3 | import java.sql.ResultSet; 4 | import java.sql.SQLException; 5 | 6 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 7 | import org.springframework.jdbc.core.RowMapper; 8 | 9 | public class PersonRowMapper implements RowMapper { 10 | 11 | @Override 12 | public Person mapRow(ResultSet rs, int arg1) throws SQLException { 13 | Person person = new Person(); 14 | person.setId(rs.getInt("ID")); 15 | person.setFirstName(rs.getString("FIRSTNAME")); 16 | person.setLastName(rs.getString("LASTNAME")); 17 | person.setDob(rs.getDate("DATEOFBIRTH")); 18 | return person; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/jdbcTemplate/person/conf/AppConfig.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.conf; 2 | 3 | import javax.sql.DataSource; 4 | 5 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Factory; 6 | import org.javaturk.spring.data.ch02.jdbc.common.domain.PersonFactory; 7 | import org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.dao.PersonJdbcTemplateDAO; 8 | //import org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.domain.Person; 9 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.context.annotation.Configuration; 13 | import org.springframework.context.annotation.Scope; 14 | import org.springframework.jdbc.core.JdbcTemplate; 15 | 16 | @Configuration 17 | public class AppConfig { 18 | 19 | @Autowired 20 | private Factory personFactory; 21 | 22 | @Autowired 23 | private DataSource dataSource1; 24 | 25 | @Bean 26 | @Scope("prototype") 27 | public Person person() { 28 | return personFactory.createPerson(); 29 | } 30 | 31 | @Bean 32 | @Scope("singleton") 33 | public PersonFactory personFactory() { 34 | return PersonFactory.getInstance(); 35 | } 36 | 37 | @Bean 38 | @Scope("prototype") 39 | public PersonJdbcTemplateDAO personJdbcTemplateDAO() { 40 | System.out.println("Creating personJdbcTemplateDAO"); 41 | return new PersonJdbcTemplateDAO(); 42 | } 43 | 44 | @Bean 45 | @Scope("prototype") 46 | public JdbcTemplate jdbcTemplate() { 47 | return new JdbcTemplate(dataSource1); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/jdbcTemplate/person/conf/JDBCConfig.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.conf; 2 | 3 | import javax.annotation.PostConstruct; 4 | import javax.sql.DataSource; 5 | 6 | import org.apache.commons.dbcp2.BasicDataSource; 7 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 8 | import org.javaturk.spring.data.ch02.jdbc.common.domain.PersonFactory; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.beans.factory.annotation.Value; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.context.annotation.Configuration; 13 | import org.springframework.context.annotation.PropertySource; 14 | import org.springframework.context.annotation.Scope; 15 | import org.springframework.core.env.Environment; 16 | 17 | @Configuration 18 | @PropertySource("org/javaturk/spring/data/ch02/spring/jdbcTemplate/person/resources/jdbc.properties") 19 | public class JDBCConfig{ 20 | 21 | @Value("${jdbc.url}") 22 | private String url; 23 | 24 | @Value("${jdbc.username}") 25 | private String username; 26 | 27 | @Value("${jdbc.password}") 28 | private String password; 29 | 30 | @Value("${jdbc.driverClassName}") 31 | private String driver; 32 | 33 | @Autowired 34 | private Environment env; 35 | 36 | @Bean 37 | @Scope("prototype") 38 | public DataSource dataSource1() { 39 | BasicDataSource basicDataSource = new BasicDataSource(); 40 | basicDataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); 41 | basicDataSource.setUrl(env.getProperty("jdbc.url")); 42 | basicDataSource.setUsername(env.getProperty("jdbc.username")); 43 | basicDataSource.setPassword(env.getProperty("jdbc.password")); 44 | return basicDataSource; 45 | } 46 | 47 | @Bean 48 | @Scope("prototype") 49 | public DataSource dataSource2() { 50 | BasicDataSource basicDataSource = new BasicDataSource(); 51 | basicDataSource.setDriverClassName(driver); 52 | basicDataSource.setUrl(url); 53 | basicDataSource.setUsername(username); 54 | basicDataSource.setPassword(password); 55 | return basicDataSource; 56 | } 57 | 58 | @PostConstruct 59 | public void listProperties() { 60 | System.err.format("\n******************************************************************************\n"); 61 | System.err.format("* %50s %25s \n", "Creating the connection with following properties", "*"); 62 | System.err.format("* %-20s %-50s %4s \n", "URL:", url, "*"); 63 | System.err.format("* %-20s %-50s %4s \n", "Username:", username, "*"); 64 | System.err.format("* %-20s %-50s %4s \n", "Password:", password, "*"); 65 | System.err.format("* %-20s %-50s %4s \n", "Driver:", driver, "*"); 66 | System.err.format("******************************************************************************\n"); 67 | System.out.println(); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/jdbcTemplate/person/dao/PersonJdbcTemplateDAO.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.dao; 2 | 3 | import java.util.List; 4 | 5 | import org.javaturk.spring.data.ch02.jdbc.common.data.PersonDAO; 6 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Factory; 7 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 8 | import org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.callback.PersonPreparedStatementIdAndDobSetter; 9 | import org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.callback.PersonPreparedStatementIdSetter; 10 | import org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.callback.PersonPreparedStatementSetter; 11 | import org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.callback.PersonRowMapper; 12 | import org.javaturk.spring.data.ch02.jdbc.common.domain.ex.NoSuchPersonException; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.jdbc.core.JdbcTemplate; 15 | 16 | public class PersonJdbcTemplateDAO implements PersonDAO { 17 | private static final String SAVE_PERSON_QUERY = "INSERT INTO PERSONS VALUES(?,?,?,?)"; 18 | private static final String COUNT_QUERY = "SELECT COUNT(*) FROM PERSONS"; 19 | private static final String RETRIEVE_PERSON_QUERY = "SELECT * FROM PERSONS WHERE ID = ?"; 20 | private static final String RETRIEVE_ALL_PERSONS_QUERY = "SELECT * FROM PERSONS"; 21 | private static final String UPDATE_PERSONDOB_QUERY = "UPDATE PERSONS SET DATEOFBIRTH = ? WHERE ID = ?"; 22 | private static final String DELETE_PERSON_QUERY = "DELETE FROM PERSONS WHERE ID = ?"; 23 | private static final String DELETE_ALL_PERSONS_QUERY = "DELETE FROM PERSONS"; 24 | 25 | @Autowired 26 | private JdbcTemplate jdbcTemplate; 27 | 28 | // @Override 29 | // public void savePerson(Person person) { 30 | // int count = jdbcTemplate.update(SAVE_PERSON_QUERY, person.getId(), person.getFirstName(), person.getLastName(), person.getDobAsSQlDate()); 31 | // if (count == 1) 32 | // System.out.println("Person has been saved."); 33 | // else 34 | // System.out.println("Problem when saving Person."); 35 | // } 36 | 37 | @Override 38 | public void savePerson(Person person) { 39 | System.out.println("\nSaving person:" + person); 40 | int count = jdbcTemplate.update(SAVE_PERSON_QUERY, new PersonPreparedStatementSetter(person)); 41 | if (count == 1) 42 | System.out.println("Person saved."); 43 | else 44 | System.out.println("Problem when saving Person."); 45 | } 46 | 47 | @Override 48 | public int retrievePersonCount() { 49 | return jdbcTemplate.queryForObject(COUNT_QUERY, Integer.class); 50 | } 51 | 52 | // @Override 53 | // public Person retrievePerson(int id) throws NoSuchPersonException { 54 | // Person person = (Person) jdbcTemplate.query(RETRIEVE_PERSON_QUERY, new PersonRowMapper(), id); 55 | // if (person.getId() == 0) 56 | // throw new NoSuchPersonException(person.getId()); 57 | // return person; 58 | // } 59 | 60 | @Override 61 | public Person retrievePerson(int id) throws NoSuchPersonException { 62 | Person person = jdbcTemplate.queryForObject(RETRIEVE_PERSON_QUERY, new PersonRowMapper(), id); 63 | return person; 64 | } 65 | 66 | @Override 67 | public List retrieveAllPersons() { 68 | return (List) jdbcTemplate.query(RETRIEVE_ALL_PERSONS_QUERY, new PersonRowMapper()); 69 | } 70 | 71 | @Override 72 | public void updatePersonDOB(Person person) { 73 | int count = jdbcTemplate.update(UPDATE_PERSONDOB_QUERY, new PersonPreparedStatementIdAndDobSetter(person)); 74 | if (count == 1) 75 | System.out.println("Person has been updated."); 76 | else 77 | System.out.println("Problem when updating Person."); 78 | } 79 | 80 | @Override 81 | public void deletePerson(Person person) { 82 | jdbcTemplate.update(DELETE_PERSON_QUERY, new PersonPreparedStatementIdSetter(person)); 83 | } 84 | 85 | @Override 86 | public void deleteAllPersons() { 87 | int count = jdbcTemplate.update(DELETE_ALL_PERSONS_QUERY); 88 | System.out.println(count + " persons has been deleted."); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/jdbcTemplate/person/resources/jdbc.properties: -------------------------------------------------------------------------------- 1 | #JDBC Properties 2 | #Please activate the suitable set of properties of your DB choice. 3 | 4 | #Oracle XE 5 | #url=jdbc:oracle:thin:@localhost:1521:XE 6 | #username=coffee 7 | #password=password 8 | #driver=oracle.jdbc.driver.OracleDriver 9 | 10 | #JavaDB (Derby) 11 | #url=jdbc:derby://localhost:1527/JPA;create=true 12 | #username=app 13 | #password=password 14 | #driver=org.apache.derby.jdbc.ClientDriver 15 | 16 | 17 | 18 | #MySQL 19 | jdbc.url:jdbc:mysql://localhost/JDBC 20 | jdbc.username=root 21 | jdbc.password=password 22 | jdbc.driverClassName=com.mysql.cj.jdbc.Driver 23 | 24 | 25 | #url:jdbc:postgresql://localhost:5432/JPA 26 | #username=postgres 27 | #password=password 28 | #driver=org.postgresql.Driver 29 | 30 | 31 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/namedParameterJdbcTemplate/person/NamedParameterJdbcTemplateTest.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.namedParameterJdbcTemplate.person; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import org.javaturk.spring.data.ch02.spring.namedParameterJdbcTemplate.person.conf.AppConfig; 7 | import org.javaturk.spring.data.ch02.spring.namedParameterJdbcTemplate.person.conf.JDBCConfig; 8 | import org.javaturk.spring.data.ch02.jdbc.common.data.PersonDAO; 9 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Factory; 10 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 11 | import org.javaturk.spring.data.ch02.jdbc.common.domain.ex.NoSuchPersonException; 12 | import org.javaturk.spring.data.ch02.jdbc.spring.SpringTest; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.beans.factory.annotation.Qualifier; 15 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 16 | import org.springframework.context.annotation.Import; 17 | 18 | @Import({ AppConfig.class, JDBCConfig.class }) 19 | public class NamedParameterJdbcTemplateTest { 20 | // This should be before personFactory otherwise "Is there an unresolvable circular reference?" 21 | @Autowired 22 | PersonDAO dao; 23 | 24 | @Autowired 25 | Factory personFactory; 26 | 27 | public static void main(String[] args) throws NoSuchPersonException { 28 | AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(NamedParameterJdbcTemplateTest.class); 29 | NamedParameterJdbcTemplateTest test = context.getBean(NamedParameterJdbcTemplateTest.class); 30 | test.run(); 31 | } 32 | 33 | public void run() throws NoSuchPersonException { 34 | System.out.println("Number of person: " + dao.retrievePersonCount()); 35 | 36 | // int id = 1; 37 | // Person person = new Person(id, "Ali", "Ozmen", new Date()); 38 | // dao.savePerson(person); 39 | 40 | // Person personRetrieved = null; 41 | // try { 42 | // personRetrieved = dao.retrievePerson(id); 43 | // System.out.println(personRetrieved); 44 | // } catch (NoSuchPersonException e) { 45 | // System.out.println("Person does not exists!"); 46 | // System.out.println(e.getMessage()); 47 | // } 48 | 49 | // dao.deletePerson(personRetrieved); 50 | 51 | savePersons(100); 52 | 53 | List persons = dao.retrieveAllPersons(); 54 | System.out.println("There are " + persons.size() + " persons.\n"); 55 | for(Person person : persons) 56 | System.out.println(person); 57 | 58 | // int id = 1; 59 | // Person person = dao.retrievePerson(id); 60 | // System.out.println("Before update: " + person); 61 | // person.setDob(new Date(2000000000)); 62 | // dao.updatePersonDOB(person); 63 | // person = dao.retrievePerson(id); 64 | // System.out.println("After update: " + person); 65 | 66 | // dao.deleteAllPersons(); 67 | } 68 | 69 | /** 70 | * Utility method to populate the database 71 | * 72 | * @param n Number of the persons to be created. 73 | */ 74 | public void savePersons(int n) { 75 | System.out.println("\nSaving " + n + " persons to DB"); 76 | for (int i = 0; i < n; i++) { 77 | Person p = personFactory.createPerson(); 78 | dao.savePerson(p); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/namedParameterJdbcTemplate/person/callback/PersonRowMapper.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.namedParameterJdbcTemplate.person.callback; 2 | 3 | import java.sql.ResultSet; 4 | import java.sql.SQLException; 5 | 6 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 7 | import org.springframework.jdbc.core.RowMapper; 8 | 9 | public class PersonRowMapper implements RowMapper { 10 | 11 | @Override 12 | public Person mapRow(ResultSet rs, int arg1) throws SQLException { 13 | Person person = new Person(); 14 | person.setId(rs.getInt("ID")); 15 | person.setFirstName(rs.getString("FIRSTNAME")); 16 | person.setLastName(rs.getString("LASTNAME")); 17 | person.setDob(rs.getDate("DATEOFBIRTH")); 18 | return person; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/namedParameterJdbcTemplate/person/callback/PersonSqlParameterSource.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.namedParameterJdbcTemplate.person.callback; 2 | 3 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 4 | import org.springframework.jdbc.core.namedparam.SqlParameterSource; 5 | 6 | public class PersonSqlParameterSource implements SqlParameterSource { 7 | private Person person; 8 | 9 | public PersonSqlParameterSource(Person person) { 10 | this.person = person; 11 | } 12 | 13 | @Override 14 | public Object getValue(String paramName) throws IllegalArgumentException { 15 | Object value = switch (paramName) { 16 | case "id" -> person.getId(); 17 | case "firstName" -> person.getFirstName(); 18 | case "lastName" -> person.getLastName(); 19 | case "dob" -> person.getDobAsSQlDate(); 20 | default -> null; 21 | }; 22 | return value; 23 | } 24 | 25 | @Override 26 | public boolean hasValue(String paramName) { 27 | return true; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/namedParameterJdbcTemplate/person/conf/AppConfig.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.namedParameterJdbcTemplate.person.conf; 2 | 3 | import javax.sql.DataSource; 4 | 5 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Factory; 6 | import org.javaturk.spring.data.ch02.jdbc.common.domain.PersonFactory; 7 | import org.javaturk.spring.data.ch02.spring.namedParameterJdbcTemplate.person.dao.PersonNamedParameterJdbcTemplateDAO; 8 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.context.annotation.Bean; 11 | import org.springframework.context.annotation.Configuration; 12 | import org.springframework.context.annotation.Scope; 13 | import org.springframework.jdbc.core.JdbcTemplate; 14 | import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; 15 | 16 | @Configuration 17 | public class AppConfig { 18 | 19 | @Autowired 20 | private Factory personFactory; 21 | 22 | @Autowired 23 | private DataSource dataSource1; 24 | 25 | @Bean 26 | @Scope("prototype") 27 | public Person person() { 28 | return personFactory.createPerson(); 29 | } 30 | 31 | @Bean 32 | @Scope("singleton") 33 | public PersonFactory personFactory() { 34 | return PersonFactory.getInstance(); 35 | } 36 | 37 | @Bean 38 | @Scope("prototype") 39 | public PersonNamedParameterJdbcTemplateDAO personNamedParameterJdbcTemplateDAO() { 40 | System.out.println("Creating personNamedParameterJdbcTemplateDAO"); 41 | return new PersonNamedParameterJdbcTemplateDAO(); 42 | } 43 | 44 | @Bean 45 | @Scope("prototype") 46 | public NamedParameterJdbcTemplate namedParameterJdbcTemplate() { 47 | return new NamedParameterJdbcTemplate(dataSource1); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/namedParameterJdbcTemplate/person/conf/JDBCConfig.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.namedParameterJdbcTemplate.person.conf; 2 | 3 | import javax.annotation.PostConstruct; 4 | import javax.sql.DataSource; 5 | 6 | import org.apache.commons.dbcp2.BasicDataSource; 7 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 8 | import org.javaturk.spring.data.ch02.jdbc.common.domain.PersonFactory; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.beans.factory.annotation.Value; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.context.annotation.Configuration; 13 | import org.springframework.context.annotation.PropertySource; 14 | import org.springframework.context.annotation.Scope; 15 | import org.springframework.core.env.Environment; 16 | 17 | @Configuration 18 | @PropertySource("org/javaturk/spring/data/ch02/spring/namedParameterJdbcTemplate/person/resources/jdbc.properties") 19 | public class JDBCConfig{ 20 | 21 | @Value("${jdbc.url}") 22 | private String url; 23 | 24 | @Value("${jdbc.username}") 25 | private String username; 26 | 27 | @Value("${jdbc.password}") 28 | private String password; 29 | 30 | @Value("${jdbc.driverClassName}") 31 | private String driver; 32 | 33 | @Autowired 34 | private Environment env; 35 | 36 | @Bean 37 | @Scope("prototype") 38 | public DataSource dataSource1() { 39 | BasicDataSource basicDataSource = new BasicDataSource(); 40 | basicDataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); 41 | basicDataSource.setUrl(env.getProperty("jdbc.url")); 42 | basicDataSource.setUsername(env.getProperty("jdbc.username")); 43 | basicDataSource.setPassword(env.getProperty("jdbc.password")); 44 | return basicDataSource; 45 | } 46 | 47 | @Bean 48 | @Scope("prototype") 49 | public DataSource dataSource2() { 50 | BasicDataSource basicDataSource = new BasicDataSource(); 51 | basicDataSource.setDriverClassName(driver); 52 | basicDataSource.setUrl(url); 53 | basicDataSource.setUsername(username); 54 | basicDataSource.setPassword(password); 55 | return basicDataSource; 56 | } 57 | 58 | @PostConstruct 59 | public void listProperties() { 60 | System.err.format("\n******************************************************************************\n"); 61 | System.err.format("* %50s %25s \n", "Creating the connection with following properties", "*"); 62 | System.err.format("* %-20s %-50s %4s \n", "URL:", url, "*"); 63 | System.err.format("* %-20s %-50s %4s \n", "Username:", username, "*"); 64 | System.err.format("* %-20s %-50s %4s \n", "Password:", password, "*"); 65 | System.err.format("* %-20s %-50s %4s \n", "Driver:", driver, "*"); 66 | System.err.format("******************************************************************************\n"); 67 | System.out.println(); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/namedParameterJdbcTemplate/person/dao/PersonNamedParameterJdbcTemplateDAO.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.namedParameterJdbcTemplate.person.dao; 2 | 3 | import java.util.Collections; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import org.javaturk.spring.data.ch02.jdbc.common.data.PersonDAO; 9 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Factory; 10 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 11 | import org.javaturk.spring.data.ch02.spring.namedParameterJdbcTemplate.person.callback.*; 12 | import org.javaturk.spring.data.ch02.jdbc.common.domain.ex.NoSuchPersonException; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.jdbc.core.JdbcTemplate; 15 | import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; 16 | 17 | public class PersonNamedParameterJdbcTemplateDAO implements PersonDAO { 18 | private static final String SAVE_PERSON_QUERY = "INSERT INTO PERSONS VALUES(:id, :firstName, :lastName, :dob)"; 19 | private static final String COUNT_QUERY = "SELECT COUNT(*) FROM PERSONS"; 20 | private static final String RETRIEVE_PERSON_QUERY = "SELECT * FROM PERSONS WHERE ID = :id"; 21 | private static final String RETRIEVE_ALL_PERSONS_QUERY = "SELECT * FROM PERSONS"; 22 | private static final String UPDATE_PERSONDOB_QUERY = "UPDATE PERSONS SET DATEOFBIRTH = :dob WHERE ID = :id"; 23 | private static final String DELETE_PERSON_QUERY = "DELETE FROM PERSONS WHERE ID = :id"; 24 | private static final String DELETE_ALL_PERSONS_QUERY = "DELETE FROM PERSONS"; 25 | 26 | @Autowired 27 | private NamedParameterJdbcTemplate namedParameterJdbcTemplate; 28 | 29 | @Autowired 30 | Factory personFactory; 31 | 32 | // @Override 33 | // public void savePerson(Person person) { 34 | // System.out.println("\nSaving person:" + person); 35 | // Map namedParameterMap = new HashMap<>(); 36 | // namedParameterMap.put("id", person.getId()); 37 | // namedParameterMap.put("firstName", person.getFirstName()); 38 | // namedParameterMap.put("lastName", person.getLastName()); 39 | // namedParameterMap.put("dob", person.getDob()); 40 | // int count = namedParameterJdbcTemplate.update(SAVE_PERSON_QUERY, namedParameterMap); 41 | // if (count == 1) 42 | // System.out.println("Person saved."); 43 | // else 44 | // System.out.println("Problem when saving Person."); 45 | // } 46 | 47 | @Override 48 | public void savePerson(Person person) { 49 | System.out.println("\nSaving person:" + person); 50 | PersonSqlParameterSource psps = new PersonSqlParameterSource(person); 51 | int count = namedParameterJdbcTemplate.update(SAVE_PERSON_QUERY, psps); 52 | if (count == 1) 53 | System.out.println("Person saved."); 54 | else 55 | System.out.println("Problem when saving Person."); 56 | } 57 | 58 | public void savePersons(int n) { 59 | System.out.println("\nSaving " + n + " persons to DB"); 60 | for (int i = 0; i < n; i++) { 61 | Person p = personFactory.createPerson(); 62 | savePerson(p); 63 | } 64 | } 65 | 66 | @Override 67 | public int retrievePersonCount() { 68 | return(int) namedParameterJdbcTemplate.queryForObject(COUNT_QUERY, new HashMap(), Integer.class); 69 | } 70 | 71 | @Override 72 | public Person retrievePerson(int id) throws NoSuchPersonException { 73 | Map namedParameterMap = Collections.singletonMap("id", id); 74 | Person person = namedParameterJdbcTemplate.queryForObject(RETRIEVE_PERSON_QUERY, namedParameterMap, new PersonRowMapper()); 75 | if (person.getId() == 0) 76 | throw new NoSuchPersonException(person.getId()); 77 | return person; 78 | } 79 | 80 | @Override 81 | public List retrieveAllPersons() { 82 | return (List) namedParameterJdbcTemplate.query(RETRIEVE_ALL_PERSONS_QUERY, new PersonRowMapper()); 83 | } 84 | 85 | @Override 86 | public void updatePersonDOB(Person person) { 87 | Map namedParameterMap = new HashMap<>(); 88 | namedParameterMap.put("id", person.getId()); 89 | namedParameterMap.put("dob", person.getDob()); 90 | int count = namedParameterJdbcTemplate.update(UPDATE_PERSONDOB_QUERY, namedParameterMap); 91 | if (count == 1) 92 | System.out.println("Person has been updated."); 93 | else 94 | System.out.println("Problem when updating Person."); 95 | } 96 | 97 | @Override 98 | public void deletePerson(Person person) { 99 | Map namedParameterMap = Collections.singletonMap("id", person.getId()); 100 | namedParameterJdbcTemplate.update(DELETE_PERSON_QUERY, namedParameterMap); 101 | } 102 | 103 | @Override 104 | public void deleteAllPersons() { 105 | int count = namedParameterJdbcTemplate.update(DELETE_ALL_PERSONS_QUERY, new HashMap()); 106 | System.out.println(count + " persons has been deleted."); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/namedParameterJdbcTemplate/person/resources/jdbc.properties: -------------------------------------------------------------------------------- 1 | #JDBC Properties 2 | #Please activate the suitable set of properties of your DB choice. 3 | 4 | #Oracle XE 5 | #url=jdbc:oracle:thin:@localhost:1521:XE 6 | #username=coffee 7 | #password=password 8 | #driver=oracle.jdbc.driver.OracleDriver 9 | 10 | #JavaDB (Derby) 11 | #url=jdbc:derby://localhost:1527/JPA;create=true 12 | #username=app 13 | #password=password 14 | #driver=org.apache.derby.jdbc.ClientDriver 15 | 16 | 17 | 18 | #MySQL 19 | jdbc.url:jdbc:mysql://localhost/JDBC 20 | jdbc.username=root 21 | jdbc.password=password 22 | jdbc.driverClassName=com.mysql.cj.jdbc.Driver 23 | 24 | 25 | #url:jdbc:postgresql://localhost:5432/JPA 26 | #username=postgres 27 | #password=password 28 | #driver=org.postgresql.Driver 29 | 30 | 31 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/simpleJdbcInsert/person/SimpleJdbcInsertTest.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.simpleJdbcInsert.person; 2 | 3 | import java.util.Date; 4 | 5 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Factory; 6 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 7 | import org.javaturk.spring.data.ch02.jdbc.common.domain.ex.NoSuchPersonException; 8 | import org.javaturk.spring.data.ch02.spring.simpleJdbcInsert.person.conf.*; 9 | import org.javaturk.spring.data.ch02.spring.simpleJdbcInsert.person.dao.PersonInsertDao; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 12 | import org.springframework.context.annotation.Import; 13 | 14 | @Import({ AppConfig.class, JDBCConfig.class }) 15 | public class SimpleJdbcInsertTest { 16 | 17 | @Autowired 18 | PersonInsertDao dao1; 19 | 20 | @Autowired 21 | PersonInsertDao dao2; 22 | 23 | @Autowired 24 | Factory personFactory; 25 | 26 | public static void main(String[] args) throws NoSuchPersonException { 27 | AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SimpleJdbcInsertTest.class); 28 | SimpleJdbcInsertTest test = context.getBean(SimpleJdbcInsertTest.class); 29 | test.run(); 30 | } 31 | 32 | public void run() throws NoSuchPersonException { 33 | int id = 160; 34 | Person person = new Person(id, "Ali", "Ozmen", new Date()); 35 | dao2.savePerson(person); 36 | 37 | id = 161; 38 | person = new Person(id, "Sami", "Tansu"); 39 | dao2.savePersonWithoutDob(person); 40 | 41 | // savePersons(100); 42 | } 43 | 44 | /** 45 | * Utility method to populate the database 46 | * 47 | * @param n Number of the persons to be created. 48 | */ 49 | public void savePersons(int n) { 50 | System.out.println("\nSaving " + n + " persons to DB"); 51 | for (int i = 0; i < n; i++) { 52 | Person p = personFactory.createPerson(); 53 | dao1.savePerson(p); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/simpleJdbcInsert/person/callback/PersonSqlParameterSource.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.simpleJdbcInsert.person.callback; 2 | 3 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 4 | import org.springframework.jdbc.core.namedparam.SqlParameterSource; 5 | 6 | public class PersonSqlParameterSource implements SqlParameterSource { 7 | private Person person; 8 | 9 | public PersonSqlParameterSource(Person person) { 10 | this.person = person; 11 | } 12 | 13 | @Override 14 | public Object getValue(String paramName) throws IllegalArgumentException { 15 | Object value = switch (paramName) { 16 | case "ID" -> person.getId(); 17 | case "FIRSTNAME" -> person.getFirstName(); 18 | case "LASTNAME" -> person.getLastName(); 19 | case "DATEOFBIRTH" -> person.getDobAsSQlDate(); 20 | default -> null; 21 | }; 22 | return value; 23 | } 24 | 25 | @Override 26 | public boolean hasValue(String paramName) { 27 | return true; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/simpleJdbcInsert/person/callback/PersonSqlParameterSourceWithoutDob.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.simpleJdbcInsert.person.callback; 2 | 3 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 4 | import org.springframework.jdbc.core.namedparam.SqlParameterSource; 5 | 6 | public class PersonSqlParameterSourceWithoutDob implements SqlParameterSource { 7 | private Person person; 8 | 9 | public PersonSqlParameterSourceWithoutDob(Person person) { 10 | this.person = person; 11 | } 12 | 13 | @Override 14 | public Object getValue(String paramName) throws IllegalArgumentException { 15 | Object value = switch (paramName) { 16 | case "ID" -> person.getId(); 17 | case "FIRSTNAME" -> person.getFirstName(); 18 | case "LASTNAME" -> person.getLastName(); 19 | default -> null; 20 | }; 21 | return value; 22 | } 23 | 24 | @Override 25 | public boolean hasValue(String arg0) { 26 | return true; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/simpleJdbcInsert/person/conf/AppConfig.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.simpleJdbcInsert.person.conf; 2 | 3 | import javax.sql.DataSource; 4 | 5 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Factory; 6 | import org.javaturk.spring.data.ch02.jdbc.common.domain.PersonFactory; 7 | import org.javaturk.spring.data.ch02.spring.namedParameterJdbcTemplate.person.dao.PersonNamedParameterJdbcTemplateDAO; 8 | import org.javaturk.spring.data.ch02.spring.simpleJdbcInsert.person.dao.*; 9 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.context.annotation.Configuration; 13 | import org.springframework.context.annotation.Scope; 14 | import org.springframework.jdbc.core.JdbcTemplate; 15 | import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; 16 | import org.springframework.jdbc.core.simple.SimpleJdbcInsert; 17 | 18 | @Configuration 19 | public class AppConfig { 20 | 21 | @Autowired 22 | private Factory personFactory; 23 | 24 | @Autowired 25 | private DataSource dataSource1; 26 | 27 | @Bean 28 | @Scope("prototype") 29 | public Person person() { 30 | return personFactory.createPerson(); 31 | } 32 | 33 | @Bean 34 | @Scope("singleton") 35 | public PersonFactory personFactory() { 36 | return PersonFactory.getInstance(); 37 | } 38 | 39 | @Bean 40 | @Scope("prototype") 41 | public SimpleJdbcInsertDao1 dao1() { 42 | System.out.println("Creating simpleJdbcInsertDao1"); 43 | return new SimpleJdbcInsertDao1(); 44 | } 45 | 46 | @Bean 47 | @Scope("prototype") 48 | public SimpleJdbcInsertDao2 dao2() { 49 | System.out.println("Creating simpleJdbcInsertDao2"); 50 | return new SimpleJdbcInsertDao2(); 51 | } 52 | 53 | @Bean 54 | @Scope("prototype") 55 | public SimpleJdbcInsert simpleJdbcInsert() { 56 | return new SimpleJdbcInsert(dataSource1); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/simpleJdbcInsert/person/conf/JDBCConfig.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.simpleJdbcInsert.person.conf; 2 | 3 | import javax.annotation.PostConstruct; 4 | import javax.sql.DataSource; 5 | 6 | import org.apache.commons.dbcp2.BasicDataSource; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | import org.springframework.context.annotation.PropertySource; 12 | import org.springframework.context.annotation.Scope; 13 | import org.springframework.core.env.Environment; 14 | 15 | @Configuration 16 | @PropertySource("org/javaturk/spring/data/ch02/spring/simpleJdbcInsert/person/resources/jdbc.properties") 17 | public class JDBCConfig{ 18 | 19 | @Value("${jdbc.url}") 20 | private String url; 21 | 22 | @Value("${jdbc.username}") 23 | private String username; 24 | 25 | @Value("${jdbc.password}") 26 | private String password; 27 | 28 | @Value("${jdbc.driverClassName}") 29 | private String driver; 30 | 31 | @Autowired 32 | private Environment env; 33 | 34 | @Bean 35 | @Scope("prototype") 36 | public DataSource dataSource1() { 37 | BasicDataSource basicDataSource = new BasicDataSource(); 38 | basicDataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); 39 | basicDataSource.setUrl(env.getProperty("jdbc.url")); 40 | basicDataSource.setUsername(env.getProperty("jdbc.username")); 41 | basicDataSource.setPassword(env.getProperty("jdbc.password")); 42 | return basicDataSource; 43 | } 44 | 45 | @Bean 46 | @Scope("prototype") 47 | public DataSource dataSource2() { 48 | BasicDataSource basicDataSource = new BasicDataSource(); 49 | basicDataSource.setDriverClassName(driver); 50 | basicDataSource.setUrl(url); 51 | basicDataSource.setUsername(username); 52 | basicDataSource.setPassword(password); 53 | return basicDataSource; 54 | } 55 | 56 | @PostConstruct 57 | public void listProperties() { 58 | System.err.format("\n******************************************************************************\n"); 59 | System.err.format("* %50s %25s \n", "Creating the connection with following properties", "*"); 60 | System.err.format("* %-20s %-50s %4s \n", "URL:", url, "*"); 61 | System.err.format("* %-20s %-50s %4s \n", "Username:", username, "*"); 62 | System.err.format("* %-20s %-50s %4s \n", "Password:", password, "*"); 63 | System.err.format("* %-20s %-50s %4s \n", "Driver:", driver, "*"); 64 | System.err.format("******************************************************************************\n"); 65 | System.out.println(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/simpleJdbcInsert/person/dao/PersonInsertDao.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.simpleJdbcInsert.person.dao; 2 | 3 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 4 | 5 | public interface PersonInsertDao { 6 | 7 | public void savePerson(Person person); 8 | 9 | public void savePersonWithoutDob(Person person); 10 | } 11 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/simpleJdbcInsert/person/dao/SimpleJdbcInsertDao1.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.simpleJdbcInsert.person.dao; 2 | 3 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 4 | import org.javaturk.spring.data.ch02.spring.simpleJdbcInsert.person.callback.PersonSqlParameterSource; 5 | import org.javaturk.spring.data.ch02.spring.simpleJdbcInsert.person.callback.PersonSqlParameterSourceWithoutDob; 6 | import org.springframework.beans.BeansException; 7 | import org.springframework.beans.factory.BeanFactory; 8 | import org.springframework.beans.factory.BeanFactoryAware; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.jdbc.core.simple.SimpleJdbcInsert; 11 | 12 | public class SimpleJdbcInsertDao1 implements PersonInsertDao, BeanFactoryAware{ 13 | 14 | @Autowired 15 | private SimpleJdbcInsert simpleJdbcInsert; 16 | 17 | private BeanFactory beanFactory; 18 | 19 | @Override 20 | public void savePerson(Person person) { 21 | System.out.println("\nSaving person:" + person); 22 | refreshSimpleJdbcInsert(); 23 | PersonSqlParameterSource psps = new PersonSqlParameterSource(person); 24 | simpleJdbcInsert.setTableName("PERSONS"); 25 | int count = simpleJdbcInsert.execute(psps); 26 | if (count == 1) 27 | System.out.println("Person saved."); 28 | else 29 | System.out.println("Problem when saving Person."); 30 | } 31 | 32 | @Override 33 | public void savePersonWithoutDob(Person person) { 34 | System.out.println("\nSaving person without Dob:" + person); 35 | refreshSimpleJdbcInsert(); 36 | PersonSqlParameterSourceWithoutDob psps = new PersonSqlParameterSourceWithoutDob(person); 37 | simpleJdbcInsert.setTableName("PERSONS"); 38 | int count = simpleJdbcInsert.execute(psps); 39 | if (count == 1) 40 | System.out.println("Person saved."); 41 | else 42 | System.out.println("Problem when saving Person."); 43 | } 44 | 45 | @Override 46 | public void setBeanFactory(BeanFactory beanFactory) throws BeansException { 47 | this.beanFactory = beanFactory; 48 | } 49 | 50 | private void refreshSimpleJdbcInsert() { 51 | simpleJdbcInsert = beanFactory.getBean(SimpleJdbcInsert.class); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/simpleJdbcInsert/person/dao/SimpleJdbcInsertDao2.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch02.spring.simpleJdbcInsert.person.dao; 2 | 3 | import javax.annotation.PostConstruct; 4 | 5 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 6 | import org.javaturk.spring.data.ch02.spring.simpleJdbcInsert.person.callback.PersonSqlParameterSource; 7 | import org.javaturk.spring.data.ch02.spring.simpleJdbcInsert.person.callback.PersonSqlParameterSourceWithoutDob; 8 | import org.springframework.beans.BeansException; 9 | import org.springframework.beans.factory.BeanFactory; 10 | import org.springframework.beans.factory.BeanFactoryAware; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.jdbc.core.simple.SimpleJdbcInsert; 13 | 14 | public class SimpleJdbcInsertDao2 implements PersonInsertDao{ 15 | 16 | @Autowired 17 | private SimpleJdbcInsert simpleJdbcInsert; 18 | 19 | @Autowired 20 | private SimpleJdbcInsert simpleJdbcInsertWithoutDob; 21 | 22 | @Override 23 | public void savePerson(Person person) { 24 | System.out.println("\nSaving person:" + person); 25 | PersonSqlParameterSource psps = new PersonSqlParameterSource(person); 26 | int count = simpleJdbcInsert.execute(psps); 27 | if (count == 1) 28 | System.out.println("Person saved."); 29 | else 30 | System.out.println("Problem when saving Person."); 31 | } 32 | 33 | @Override 34 | public void savePersonWithoutDob(Person person) { 35 | System.out.println("\nSaving person without Dob:" + person); 36 | PersonSqlParameterSourceWithoutDob psps = new PersonSqlParameterSourceWithoutDob(person); 37 | int count = simpleJdbcInsertWithoutDob.execute(psps); 38 | if (count == 1) 39 | System.out.println("Person saved."); 40 | else 41 | System.out.println("Problem when saving Person."); 42 | } 43 | 44 | @PostConstruct 45 | public void init() { 46 | simpleJdbcInsert.setTableName("PERSONS"); 47 | simpleJdbcInsertWithoutDob.setTableName("PERSONS"); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch02/spring/simpleJdbcInsert/person/resources/jdbc.properties: -------------------------------------------------------------------------------- 1 | #JDBC Properties 2 | #Please activate the suitable set of properties of your DB choice. 3 | 4 | #Oracle XE 5 | #url=jdbc:oracle:thin:@localhost:1521:XE 6 | #username=coffee 7 | #password=password 8 | #driver=oracle.jdbc.driver.OracleDriver 9 | 10 | #JavaDB (Derby) 11 | #url=jdbc:derby://localhost:1527/JPA;create=true 12 | #username=app 13 | #password=password 14 | #driver=org.apache.derby.jdbc.ClientDriver 15 | 16 | 17 | 18 | #MySQL 19 | jdbc.url:jdbc:mysql://localhost/JDBC 20 | jdbc.username=root 21 | jdbc.password=password 22 | jdbc.driverClassName=com.mysql.cj.jdbc.Driver 23 | 24 | 25 | #url:jdbc:postgresql://localhost:5432/JPA 26 | #username=postgres 27 | #password=password 28 | #driver=org.postgresql.Driver 29 | 30 | 31 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/Readme.txt: -------------------------------------------------------------------------------- 1 | This package is about Spring Data JPA. 2 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/common/dao/PersonDao.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.common.dao; 2 | 3 | import java.util.List; 4 | 5 | import org.javaturk.spring.data.ch03.common.domain.Person; 6 | import org.javaturk.spring.data.ch03.common.domain.ex.NoSuchPersonException; 7 | 8 | public interface PersonDao { 9 | 10 | public void savePerson(Person person); 11 | 12 | public int retrievePersonCount(); 13 | 14 | public Person retrievePerson(int id) throws NoSuchPersonException; 15 | 16 | public List retrieveAllPersons(); 17 | 18 | public void updatePersonDOB(Person person); 19 | 20 | public void deletePerson(Person person); 21 | 22 | public void deleteAllPersons(); 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/common/domain/Factory.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.common.domain; 2 | 3 | public interface Factory { 4 | 5 | public Person createPerson(); 6 | } 7 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/common/domain/Person.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.common.domain; 2 | 3 | import java.util.Date; 4 | 5 | public class Person { 6 | private int id; 7 | private String firstName; 8 | private String lastName; 9 | private Date dob; 10 | 11 | public Person() { 12 | } 13 | 14 | public Person(String firstName, String lastName) { 15 | this(0, firstName, lastName, null); 16 | } 17 | 18 | public Person(int id, String firstName, String lastName, Date dob) { 19 | this.id = id; 20 | this.firstName = firstName; 21 | this.lastName = lastName; 22 | this.dob = dob; 23 | } 24 | 25 | public Person(int id, String firstName, String lastName) { 26 | this(id, firstName, lastName, null); 27 | } 28 | 29 | public Person(int id) { 30 | this(id, null, null, null); 31 | } 32 | 33 | public int getId() { 34 | return id; 35 | } 36 | 37 | public void setId(int id) { 38 | this.id = id; 39 | } 40 | 41 | public String getFirstName() { 42 | return firstName; 43 | } 44 | 45 | public void setFirstName(String firstName) { 46 | this.firstName = firstName; 47 | } 48 | 49 | public String getLastName() { 50 | return lastName; 51 | } 52 | 53 | public void setLastName(String lastName) { 54 | this.lastName = lastName; 55 | } 56 | 57 | public Date getDob() { 58 | return dob; 59 | } 60 | 61 | public void setDob(Date dob) { 62 | this.dob = dob; 63 | } 64 | 65 | public java.sql.Date getDobAsSQlDate() { 66 | return new java.sql.Date(dob.getTime()); 67 | } 68 | 69 | @Override 70 | public int hashCode() { 71 | final int prime = 31; 72 | int result = 1; 73 | result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); 74 | result = prime * result + id; 75 | result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); 76 | return result; 77 | } 78 | 79 | @Override 80 | public boolean equals(Object obj) { 81 | if (this == obj) 82 | return true; 83 | if (obj == null) 84 | return false; 85 | if (getClass() != obj.getClass()) 86 | return false; 87 | Person other = (Person) obj; 88 | if (firstName == null) { 89 | if (other.firstName != null) 90 | return false; 91 | } else if (!firstName.equals(other.firstName)) 92 | return false; 93 | if (id != other.id) 94 | return false; 95 | if (lastName == null) { 96 | if (other.lastName != null) 97 | return false; 98 | } else if (!lastName.equals(other.lastName)) 99 | return false; 100 | return true; 101 | } 102 | 103 | @Override 104 | public String toString() { 105 | return "Person [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + "]"; 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/common/domain/PersonFactory.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.common.domain; 2 | 3 | import java.util.Calendar; 4 | import java.util.Date; 5 | import java.util.Random; 6 | 7 | public class PersonFactory implements Factory{ 8 | private static PersonFactory personFactory = new PersonFactory(); 9 | private static Random random = new Random(); 10 | 11 | private static String[] firstnames = { "Ali", "Ayse", "Bahar", "Cem", "Demet", "Eylem", "Faruk", "Fatma", "Ganime", 12 | "Haydar", "Halil", "Ismail", "Jale", "Kemal", "Leman", "Mustafa", "Nedim", "Nilufer", "Selim", "Selman", 13 | "Sevda", "Tarik", "Teoman", "Yeliz", "Zuhal" }; 14 | private static String[] lastnames = { "Arabaci", "Aslan", "Batur", "Bulut", "Ceviz", "Karli", "Lale", "Ozturk", 15 | "Pasa", "Sari", "Serim", "Telli", "Torbaci", "Yazar", "Zafer" }; 16 | 17 | private PersonFactory() {} 18 | 19 | public static PersonFactory getInstance() { 20 | return personFactory; 21 | } 22 | 23 | @Override 24 | public Person createPerson() { 25 | Person person = new Person(); 26 | person.setId(createId()); 27 | person.setFirstName(createFirstName()); 28 | person.setLastName(createLastName()); 29 | person.setDob(createDob()); 30 | return person; 31 | } 32 | 33 | private int createId() { 34 | int randomInt = random.nextInt(); 35 | if (randomInt < 0) 36 | randomInt = -randomInt; 37 | return randomInt; 38 | } 39 | 40 | private String createFirstName() { 41 | int randomInt = random.nextInt(25); 42 | return firstnames[randomInt]; 43 | } 44 | 45 | private String createLastName() { 46 | int randomInt = random.nextInt(15); 47 | return lastnames[randomInt]; 48 | } 49 | 50 | private Date createDob() { 51 | Calendar calendar = Calendar.getInstance(); 52 | calendar.set(1950 + random.nextInt(60), random.nextInt(11), random.nextInt(30)); 53 | return calendar.getTime(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/common/domain/ex/NoSuchPersonException.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.common.domain.ex; 2 | 3 | public class NoSuchPersonException extends Exception{ 4 | private static String message = "No such person found! Id: "; 5 | 6 | public NoSuchPersonException(int id) { 7 | super(message + id); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/jpa/basic/PersonJpaDaoTest.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.jpa.basic; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import org.javaturk.spring.data.ch03.common.dao.PersonDao; 7 | import org.javaturk.spring.data.ch03.common.domain.Factory; 8 | import org.javaturk.spring.data.ch03.common.domain.Person; 9 | import org.javaturk.spring.data.ch03.common.domain.PersonFactory; 10 | import org.javaturk.spring.data.ch03.common.domain.ex.NoSuchPersonException; 11 | import org.javaturk.spring.data.ch03.jpa.basic.dao.PersonJpaDao; 12 | 13 | public class PersonJpaDaoTest { 14 | private PersonDao dao = new PersonJpaDao(); 15 | private Factory personFactory; 16 | 17 | public static void main(String[] args) throws NoSuchPersonException { 18 | PersonJpaDaoTest test = new PersonJpaDaoTest(); 19 | test.run(); 20 | } 21 | 22 | public void run() throws NoSuchPersonException { 23 | // System.out.println("Number of person: " + dao.retrievePersonCount()); 24 | 25 | // int id = 3; 26 | // Person person2 = new Person(id, "Ali", "Ozmen", new Date()); 27 | // dao.savePerson(person2); 28 | // 29 | // Person personRetrieved = null; 30 | // try { 31 | // personRetrieved = dao.retrievePerson(id); 32 | // System.out.println(personRetrieved); 33 | // } catch (NoSuchPersonException e) { 34 | // System.out.println("Person does not exists!"); 35 | // System.out.println(e.getMessage()); 36 | // } 37 | 38 | // dao.deletePerson(personRetrieved); 39 | 40 | savePersons(100); 41 | 42 | List persons = dao.retrieveAllPersons(); 43 | for(Person person : persons) 44 | System.out.println(person); 45 | 46 | // int id = 12481773; 47 | // Person person = dao.retrievePerson(id); 48 | // System.out.println("Before update: " + person); 49 | // person.setDob(new Date(2000000000)); 50 | // dao.updatePersonDOB(person); 51 | // person = dao.retrievePerson(id); 52 | // System.out.println("After update: " + person); 53 | 54 | // dao.deleteAllPersons(); 55 | } 56 | 57 | /* 58 | * Utility method to populate the database 59 | * 60 | * @param n Number of the persons to be created. 61 | */ 62 | public void savePersons(int n) { 63 | System.out.println("\nSaving " + n + " persons to DB"); 64 | PersonFactory personFactory = PersonFactory.getInstance(); 65 | for (int i = 0; i < n; i++) { 66 | Person p = personFactory.createPerson(); 67 | dao.savePerson(p); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/jpa/basic/dao/PersonJpaDao.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.jpa.basic.dao; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import javax.persistence.EntityManager; 7 | import javax.persistence.EntityTransaction; 8 | import javax.persistence.Query; 9 | 10 | import org.javaturk.spring.data.ch03.common.dao.PersonDao; 11 | import org.javaturk.spring.data.ch03.common.domain.Person; 12 | import org.javaturk.spring.data.ch03.common.domain.ex.NoSuchPersonException; 13 | import org.javaturk.spring.data.ch03.jpa.basic.util.PersistenceUtil; 14 | 15 | public class PersonJpaDao implements PersonDao { 16 | 17 | public PersonJpaDao() { 18 | PersistenceUtil.setPersistenceUnitName("ch03_1"); 19 | } 20 | 21 | @Override 22 | public void savePerson(Person person) { 23 | System.out.println("Saving person:" + person + "\n"); 24 | EntityManager em = PersistenceUtil.getEntityManager(); 25 | 26 | EntityTransaction tx = em.getTransaction(); 27 | tx.begin(); 28 | em.persist(person); 29 | tx.commit(); 30 | em.close(); 31 | 32 | System.out.println("Person saved!"); 33 | } 34 | 35 | @Override 36 | public Person retrievePerson(int id) throws NoSuchPersonException{ 37 | System.out.println("Retrieving the person with id = " + id); 38 | EntityManager em = PersistenceUtil.getEntityManager(); 39 | 40 | Person personRetrieved = em.find(Person.class, id); 41 | em.close(); 42 | if (personRetrieved == null) { 43 | System.out.println("No such person with id = " + id); 44 | throw new NoSuchPersonException(id); 45 | } else { 46 | return personRetrieved; 47 | } 48 | } 49 | 50 | @Override 51 | public int retrievePersonCount() { 52 | System.out.println("\nRetrieving all persons by query."); 53 | EntityManager em = PersistenceUtil.getEntityManager(); 54 | Query allPersons = em.createQuery("Select p from Person p"); 55 | List persons = allPersons.getResultList(); 56 | int size = persons.size(); 57 | em.close(); 58 | return size; 59 | } 60 | 61 | @Override 62 | public List retrieveAllPersons() { 63 | System.out.println("\nRetrieving all persons by query."); 64 | EntityManager em = PersistenceUtil.getEntityManager(); 65 | Query allPersons = em.createQuery("Select p from Person p"); 66 | List persons = allPersons.getResultList(); 67 | System.out.println(persons.size() + " objects:"); 68 | em.close(); 69 | return persons; 70 | } 71 | 72 | @Override 73 | public void updatePersonDOB(Person person) { 74 | System.out.println("Updating a person's date of birth:" + person); 75 | EntityManager em = PersistenceUtil.getEntityManager(); 76 | EntityTransaction tx = em.getTransaction(); 77 | tx.begin(); 78 | Person updatedPerson = em.merge(person); 79 | if(updatedPerson == null){ 80 | System.out.println("No such person with id = " + person.getId()); 81 | System.out.println("No person updated!"); 82 | } 83 | else 84 | System.out.println("Person updated!"); 85 | tx.commit(); 86 | em.close(); 87 | 88 | } 89 | 90 | @Override 91 | public void deletePerson(Person person) { 92 | System.out.println("Deleting a person:" + person); 93 | EntityManager em = PersistenceUtil.getEntityManager(); 94 | EntityTransaction tx = em.getTransaction(); 95 | tx.begin(); 96 | Person personToDelete = em.find(Person.class, person.getId()); 97 | if(personToDelete == null){ 98 | System.out.println("No such person with id = " + person.getId()); 99 | System.out.println("No person deleted!"); 100 | } 101 | else{ 102 | em.remove(personToDelete); 103 | System.out.println("Person deleted!"); 104 | } 105 | tx.commit(); 106 | em.close(); 107 | } 108 | 109 | @Override 110 | public void deleteAllPersons() { 111 | System.out.println("Deleting all persons."); 112 | EntityManager em = PersistenceUtil.getEntityManager(); 113 | EntityTransaction tx = em.getTransaction(); 114 | tx.begin(); 115 | Query allPersons = em.createQuery("Select p from Person p"); 116 | List persons = allPersons.getResultList(); 117 | for(Person person:persons) 118 | em.remove(person); 119 | System.out.println(persons.size() + " persons deleted!"); 120 | tx.commit(); 121 | em.close(); 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/jpa/basic/resources/jpa.properties: -------------------------------------------------------------------------------- 1 | # JPA Properties 2 | # Provider 3 | javax.persistence.provider=org.eclipse.persistence.jpa.PersistenceProvider 4 | #javax.persistence.provider=org.hibernate.jpa.HibernatePersistenceProvider 5 | # 6 | 7 | # Please activate the suitable set of properties of your DB choice 8 | 9 | #JavaDB (Derby) 10 | #javax.persistence.jdbc.url=jdbc:derby://localhost:1527/JPA;create=true 11 | #javax.persistence.jdbc.user=app 12 | #javax.persistence.jdbc.password=password 13 | #javax.persistence.jdbc.driver=org.apache.derby.jdbc.ClientDriver 14 | #javax.persistence.schema-generation.database.action=drop-and-create 15 | # none, create, drop-and-create, drop 16 | 17 | #MySQL 18 | javax.persistence.jdbc.url=jdbc:mysql://localhost/JPA?useSSL=false 19 | javax.persistence.jdbc.user=root 20 | javax.persistence.jdbc.password=password 21 | javax.persistence.jdbc.driver=com.mysql.cj.jdbc.Driver 22 | #javax.persistence.schema-generation.database.action=drop-and-create 23 | 24 | ##PostgreSQL 25 | #javax.persistence.jdbc.url=jdbc:postgresql://localhost:5432/JPA 26 | #javax.persistence.jdbc.user=postgres 27 | #javax.persistence.jdbc.password=password 28 | #javax.persistence.jdbc.driver=org.postgresql.Driver 29 | #javax.persistence.schema-generation.database.action=create 30 | 31 | 32 | #https://wiki.eclipse.org/EclipseLink/Examples/JPA/Logging 33 | #eclipselink.logging.logger=DefaultLogger 34 | #eclipselink.logging.level.sql=FINE 35 | #eclipselink.logging.level=INFO 36 | #eclipselink.logging.thread=true 37 | #eclipselink.logging.session 38 | #eclipselink.logging.timestamp 39 | #eclipselink.logging.exceptions 40 | # 41 | 42 | #eclipselink.weaving.lazy=true 43 | #eclipselink.weaving=false 44 | #eclipselink.weaving.lazy=false 45 | #weaving.eager=true 46 | #eclipselink.weaving.lazy=true 47 | #eclipselink.weaving.eager=true 48 | # 49 | hibernate.show_sql=true 50 | hibernate.format_sql=true 51 | #hibernate.enableLazyInitialization=true 52 | #hibernate.dialect=DerbyDialect 53 | #hibernate.enable_lazy_load_no_trans=false 54 | #hibernate.ejb.use_class_enhancer=true 55 | 56 | #Oracle XE 57 | #javax.persistence.jdbc.url=jdbc:oracle:thin:@localhost:1521:xe 58 | #javax.persistence.jdbc.user=jpa 59 | #javax.persistence.jdbc.password=password 60 | #javax.persistence.jdbc.driver=oracle.jdbc.driver.OracleDriver 61 | 62 | #HSQLDB 63 | #javax.persistence.jdbc.url=jdbc:hsqldb:hsql:JpaDB 64 | #javax.persistence.jdbc.user=SA 65 | #javax.persistence.jdbc.password= 66 | #javax.persistence.jdbc.driver=org.hsqldb.jdbc.JDBCDriver 67 | 68 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/jpa/basic/uml/CD.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/src/org/javaturk/spring/data/ch03/jpa/basic/uml/CD.png -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/jpa/basic/util/PersistenceUtil.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.jpa.basic.util; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.io.FileReader; 5 | import java.io.IOException; 6 | import java.util.Map.Entry; 7 | import java.util.Properties; 8 | import java.util.Set; 9 | 10 | import javax.persistence.EntityManager; 11 | import javax.persistence.EntityManagerFactory; 12 | import javax.persistence.Persistence; 13 | 14 | import org.eclipse.persistence.config.PersistenceUnitProperties; 15 | 16 | public class PersistenceUtil { 17 | 18 | private static String persistenceUnitName; 19 | private static Properties properties = new Properties(); 20 | private static String provider; 21 | private static EntityManagerFactory entityManagerFactory; 22 | 23 | //To load properties 24 | static{ 25 | try(FileReader reader = new FileReader("/Users/akin/Java/Eclipse/202003/workspace/Spring WS/Spring Data/src/org/javaturk/spring/data/ch03/jpa/basic/resources/jpa.properties")) { 26 | properties.load(reader); 27 | } catch (FileNotFoundException e) { 28 | System.out.println("Properties file not found!"); 29 | } catch (IOException e) { 30 | System.out.println("Problem when reading properties file!"); 31 | } 32 | } 33 | 34 | /** 35 | * Sets the persistence unit name so that by calling getEntityManager() a new EntityManager instance can be received. 36 | * @param persistenceUnitName 37 | */ 38 | public static void setPersistenceUnitName(String persistenceUnitName){ 39 | PersistenceUtil.persistenceUnitName = persistenceUnitName; 40 | 41 | entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName, properties); 42 | 43 | String databaseActionString = properties.getProperty("javax.persistence.schema-generation.database.action"); 44 | String databaseAction = "--"; 45 | if(databaseActionString != null) 46 | databaseAction = databaseActionString; 47 | 48 | Set keys = properties.keySet(); 49 | 50 | System.out.format("******************************************************************************\n"); 51 | System.out.format("* %50s %20s \n", "Creating the persistence unit with following properties", "*"); 52 | System.out.format("* %-20s %-50s %4s \n", "Unit name:", persistenceUnitName, "*"); 53 | System.out.format("* %-20s %-50s %4s \n", "Provider:", properties.getProperty("javax.persistence.provider"), "*"); 54 | System.out.format("* %-20s %-50s %4s \n", "URL:", properties.getProperty("javax.persistence.jdbc.url"), "*"); 55 | System.out.format("* %-20s %-50s %4s \n", "Username:", properties.getProperty("javax.persistence.jdbc.user"), "*"); 56 | System.out.format("* %-20s %-50s %4s \n", "Password:", properties.getProperty("javax.persistence.jdbc.password"), "*"); 57 | System.out.format("* %-20s %-50s %4s \n", "Driver:", properties.getProperty("javax.persistence.jdbc.driver"), "*"); 58 | System.out.format("* %-20s %-50s %4s \n", "Database action:", databaseAction, "*"); 59 | System.out.format("* %-70s %5s \n", " * * * Other Properties * * * ", "*"); 60 | 61 | for(Object key : keys) { 62 | String stringKey = (String) key; 63 | if(!stringKey.startsWith("javax")) 64 | System.out.format("* %-50s %-20s %4s \n", stringKey + ":", properties.getProperty(stringKey), "*"); 65 | } 66 | System.out.format("******************************************************************************\n"); 67 | } 68 | 69 | /** 70 | * Get the name of the persistence unit. 71 | * @return Name of the persistence unit 72 | */ 73 | public static String getPersistenceUnitName() { 74 | return persistenceUnitName; 75 | } 76 | 77 | /** 78 | * Get EntityManagerFactory created with the persistence unit data. 79 | * @return EntityManagerFactory instance created. 80 | */ 81 | public static EntityManagerFactory getEntityManagerFactory(){ 82 | return entityManagerFactory; 83 | } 84 | 85 | /** 86 | * Use this method in multi-threaded environment. It is synchronized. 87 | * @param persistenceUnitName Persistence unit name for which an EntityManager instance is created. 88 | * @return EntityManager instance created. 89 | */ 90 | public static synchronized EntityManagerFactory getEntityManagerFactory(String persistenceUnitName){ 91 | setPersistenceUnitName(persistenceUnitName); 92 | return entityManagerFactory; 93 | } 94 | 95 | public static EntityManager getEntityManager(){ 96 | return entityManagerFactory.createEntityManager(); 97 | } 98 | 99 | /** 100 | * This method is about turning on/off EclipseLink's extension for weaving in order to enable 101 | * lazy fetching for example for Basic types. 102 | * @param b true to enable lazy loading. 103 | */ 104 | // public static void turnOnEclipseLinkWeaving(boolean b) { 105 | // properties.put(PersistenceUnitProperties.WEAVING, "false"); 106 | // } 107 | 108 | /** 109 | * Just to test the class quickly. 110 | * @param args 111 | */ 112 | public static void main(String[] args) { 113 | System.out.println("In main"); 114 | setPersistenceUnitName("ch01"); 115 | } 116 | 117 | public static void close() { 118 | entityManagerFactory.close(); 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/jpa/spring/PersonJpaDaoSpringTest.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.jpa.spring; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import org.javaturk.spring.data.ch03.jpa.spring.conf.*; 7 | import org.javaturk.spring.data.ch03.jpa.spring.dao.PersonDao; 8 | import org.javaturk.spring.data.ch03.jpa.spring.domain.*; 9 | import org.javaturk.spring.data.ch03.jpa.spring.domain.ex.NoSuchPersonException; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 12 | import org.springframework.context.annotation.Import; 13 | 14 | @Import({ AppConfig.class, JPAConfig.class }) 15 | public class PersonJpaDaoSpringTest { 16 | 17 | private static AnnotationConfigApplicationContext context; 18 | private PersonDao dao; 19 | 20 | public static void main(String[] args) throws NoSuchPersonException { 21 | context = new AnnotationConfigApplicationContext(PersonJpaDaoSpringTest.class); 22 | PersonJpaDaoSpringTest test = context.getBean(PersonJpaDaoSpringTest.class); 23 | test.dao = context.getBean(PersonDao.class); 24 | test.run(); 25 | } 26 | 27 | public void run() throws NoSuchPersonException { 28 | System.out.println("Number of person: " + dao.retrievePersonCount()); 29 | 30 | // int id = 1; 31 | // Person person2 = new Person(id, "Ali", "Ozmen", new Date()); 32 | // dao.savePerson(person2); 33 | 34 | // Person personRetrieved = null; 35 | // try { 36 | // personRetrieved = dao.retrievePerson(id); 37 | // System.out.println(personRetrieved); 38 | // } catch (NoSuchPersonException e) { 39 | // System.out.println("Person does not exists!"); 40 | // System.out.println(e.getMessage()); 41 | // } 42 | 43 | // dao.deletePerson(personRetrieved); 44 | 45 | // savePersons(100); 46 | 47 | // List persons = dao.retrieveAllPersons(); 48 | // for(Person person : persons) 49 | // System.out.println(person); 50 | 51 | // int id = 1356865398; 52 | // Person person = dao.retrievePerson(id); 53 | // System.out.println("Before update: " + person); 54 | // person.setDob(new Date(2000000000)); 55 | // dao.updatePersonDOB(person); 56 | // person = dao.retrievePerson(id); 57 | // System.out.println("After update: " + person); 58 | 59 | dao.deleteAllPersons(); 60 | } 61 | 62 | /* 63 | * Utility method to populate the database 64 | * 65 | * @param n Number of the persons to be created. 66 | */ 67 | public void savePersons(int n) { 68 | System.out.println("\nSaving " + n + " persons to DB"); 69 | Factory personFactory = context.getBean(Factory.class); 70 | for (int i = 0; i < n; i++) { 71 | Person p = personFactory.createPerson(); 72 | dao.savePerson(p); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/jpa/spring/conf/AppConfig.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.jpa.spring.conf; 2 | 3 | import org.javaturk.spring.data.ch03.jpa.spring.dao.*; 4 | import org.javaturk.spring.data.ch03.jpa.spring.domain.Factory; 5 | import org.javaturk.spring.data.ch03.jpa.spring.domain.PersonFactory; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.context.annotation.Scope; 9 | 10 | @Configuration 11 | public class AppConfig { 12 | 13 | @Bean 14 | @Scope("prototype") 15 | public PersonJpaSpringDao PersonJpaSpringDao() { 16 | System.out.println("Creating PersonJpaSpringDao"); 17 | return new PersonJpaSpringDao(); 18 | } 19 | 20 | @Bean 21 | @Scope("prototype") 22 | public Factory personFactory() { 23 | System.out.println("Creating PersonFactory"); 24 | return PersonFactory.getInstance(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/jpa/spring/conf/JPAConfig.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.jpa.spring.conf; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.SQLException; 6 | import java.util.*; 7 | 8 | import javax.annotation.PostConstruct; 9 | import javax.persistence.EntityManager; 10 | import javax.persistence.EntityManagerFactory; 11 | import javax.persistence.Persistence; 12 | import javax.sql.DataSource; 13 | 14 | import org.apache.commons.dbcp2.BasicDataSource; 15 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 16 | import org.javaturk.spring.data.ch02.jdbc.common.domain.PersonFactory; 17 | import org.springframework.beans.factory.annotation.Autowired; 18 | import org.springframework.beans.factory.annotation.Value; 19 | import org.springframework.context.annotation.Bean; 20 | import org.springframework.context.annotation.Configuration; 21 | import org.springframework.context.annotation.PropertySource; 22 | import org.springframework.context.annotation.Scope; 23 | import org.springframework.core.env.Environment; 24 | import org.springframework.core.env.MapPropertySource; 25 | import org.springframework.core.env.*; 26 | 27 | @Configuration 28 | @PropertySource("org/javaturk/spring/data/ch03/jpa/spring/resources/jpa.properties") 29 | public class JPAConfig { 30 | 31 | @Value("${unitName}") 32 | private String unitName; 33 | 34 | @Value("${javax.persistence.provider}") 35 | private String provider; 36 | 37 | @Value("${javax.persistence.jdbc.url}") 38 | private String url; 39 | 40 | @Value("${javax.persistence.jdbc.user}") 41 | private String user; 42 | 43 | @Value("${javax.persistence.jdbc.password}") 44 | private String password; 45 | 46 | @Value("${javax.persistence.jdbc.driver}") 47 | private String driver; 48 | 49 | @Value("${javax.persistence.schema-generation.database.action}") 50 | private String action; 51 | 52 | @Autowired 53 | private Environment env; 54 | 55 | private Map properties; 56 | 57 | @Autowired 58 | private EntityManagerFactory entityManagerFactory; 59 | 60 | @Bean 61 | public Map properties() { 62 | properties = new HashMap<>(); 63 | properties.put("javax.persistence.provider", provider); 64 | properties.put("javax.persistence.jdbc.url", url); 65 | properties.put("javax.persistence.jdbc.driver", driver); 66 | properties.put("javax.persistence.jdbc.user", user); 67 | properties.put("javax.persistence.jdbc.password", password); 68 | // properties.forEach((k, v) -> System.out.println(k + " " + v)); 69 | return properties; 70 | } 71 | 72 | @Bean 73 | public EntityManagerFactory entityManagerFactory() { 74 | entityManagerFactory = Persistence.createEntityManagerFactory(unitName, properties()); 75 | return entityManagerFactory; 76 | } 77 | 78 | @Bean 79 | public EntityManager entityManager() { 80 | return entityManagerFactory.createEntityManager(); 81 | } 82 | 83 | @PostConstruct 84 | public void listProperties() { 85 | System.out.format("******************************************************************************\n"); 86 | System.out.format("* %50s %20s \n", "Creating the persistence unit with following properties", "*"); 87 | System.out.format("* %-20s %-50s %4s \n", "Unit name:", unitName, "*"); 88 | System.out.format("* %-20s %-50s %4s \n", "Provider:", provider, "*"); 89 | System.out.format("* %-20s %-50s %4s \n", "URL:", url, "*"); 90 | System.out.format("* %-20s %-50s %4s \n", "Username:", user, "*"); 91 | System.out.format("* %-20s %-50s %4s \n", "Password:", password, "*"); 92 | System.out.format("* %-20s %-50s %4s \n", "Driver:", driver, "*"); 93 | System.out.format("* %-20s %-50s %4s \n", "Database action:", action, "*"); 94 | // System.out.format("* %-70s %5s \n", " * * * Other Properties * * * ", "*"); 95 | 96 | // Set keys = properties.keySet(); 97 | // for(Object key : keys) { 98 | // String stringKey = (String) key; 99 | // if(!stringKey.startsWith("javax")) 100 | // System.out.format("* %-50s %-20s %4s \n", stringKey + ":", properties.get(stringKey), "*"); 101 | // } 102 | System.out.format("******************************************************************************\n"); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/jpa/spring/dao/PersonDao.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.jpa.spring.dao; 2 | 3 | import java.util.List; 4 | 5 | import org.javaturk.spring.data.ch03.jpa.spring.domain.Person; 6 | import org.javaturk.spring.data.ch03.jpa.spring.domain.ex.NoSuchPersonException; 7 | 8 | 9 | public interface PersonDao { 10 | 11 | public void savePerson(Person person); 12 | 13 | public int retrievePersonCount(); 14 | 15 | public Person retrievePerson(int id) throws NoSuchPersonException; 16 | 17 | public List retrieveAllPersons(); 18 | 19 | public void updatePersonDOB(Person person); 20 | 21 | public void deletePerson(Person person); 22 | 23 | public void deleteAllPersons(); 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/jpa/spring/dao/PersonJpaSpringDao.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.jpa.spring.dao; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import javax.persistence.EntityManager; 7 | import javax.persistence.EntityManagerFactory; 8 | import javax.persistence.EntityTransaction; 9 | import javax.persistence.Query; 10 | 11 | import org.javaturk.spring.data.ch03.jpa.spring.domain.*; 12 | import org.javaturk.spring.data.ch03.jpa.spring.domain.ex.NoSuchPersonException; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | 15 | public class PersonJpaSpringDao implements PersonDao { 16 | 17 | @Autowired 18 | private EntityManagerFactory entityManagerFactory; 19 | 20 | @Override 21 | public void savePerson(Person person) { 22 | System.out.println("Saving person:" + person + "\n"); 23 | EntityManager em = entityManagerFactory.createEntityManager(); 24 | EntityTransaction tx = em.getTransaction(); 25 | tx.begin(); 26 | em.persist(person); 27 | tx.commit(); 28 | em.close(); 29 | 30 | System.out.println("Person saved!"); 31 | } 32 | 33 | @Override 34 | public Person retrievePerson(int id) throws NoSuchPersonException{ 35 | System.out.println("Retrieving the person with id = " + id); 36 | EntityManager em = entityManagerFactory.createEntityManager(); 37 | Person personRetrieved = em.find(Person.class, id); 38 | em.close(); 39 | if (personRetrieved == null) { 40 | System.out.println("No such person with id = " + id); 41 | throw new NoSuchPersonException(id); 42 | } else { 43 | return personRetrieved; 44 | } 45 | } 46 | 47 | @Override 48 | public int retrievePersonCount() { 49 | System.out.println("\nRetrieving all persons by query."); 50 | EntityManager em = entityManagerFactory.createEntityManager(); 51 | Query allPersons = em.createQuery("Select p from Person p"); 52 | List persons = allPersons.getResultList(); 53 | int size = persons.size(); 54 | em.close(); 55 | return size; 56 | } 57 | 58 | @Override 59 | public List retrieveAllPersons() { 60 | System.out.println("\nRetrieving all persons by query."); 61 | EntityManager em = entityManagerFactory.createEntityManager(); 62 | Query allPersons = em.createQuery("Select p from Person p"); 63 | List persons = allPersons.getResultList(); 64 | System.out.println(persons.size() + " objects:"); 65 | em.close(); 66 | return persons; 67 | } 68 | 69 | @Override 70 | public void updatePersonDOB(Person person) { 71 | System.out.println("\nUpdating a person's date of birth:" + person); 72 | EntityManager em = entityManagerFactory.createEntityManager(); 73 | EntityTransaction tx = em.getTransaction(); 74 | tx.begin(); 75 | Person updatedPerson = em.merge(person); 76 | if(updatedPerson == null){ 77 | System.out.println("No such person with id = " + person.getId()); 78 | System.out.println("No person updated!"); 79 | } 80 | else 81 | System.out.println("Person updated!"); 82 | tx.commit(); 83 | em.close(); 84 | 85 | } 86 | 87 | @Override 88 | public void deletePerson(Person person) { 89 | System.out.println("\nDeleting a person:" + person); 90 | EntityManager em = entityManagerFactory.createEntityManager(); 91 | EntityTransaction tx = em.getTransaction(); 92 | tx.begin(); 93 | Person personToDelete = em.find(Person.class, person.getId()); 94 | if(personToDelete == null){ 95 | System.out.println("No such person with id = " + person.getId()); 96 | System.out.println("No person deleted!"); 97 | } 98 | else{ 99 | em.remove(personToDelete); 100 | System.out.println("Person deleted!"); 101 | } 102 | tx.commit(); 103 | em.close(); 104 | } 105 | 106 | @Override 107 | public void deleteAllPersons() { 108 | System.out.println("\nDeleting all persons."); 109 | EntityManager em = entityManagerFactory.createEntityManager(); 110 | EntityTransaction tx = em.getTransaction(); 111 | tx.begin(); 112 | Query allPersons = em.createQuery("Select p from Person p"); 113 | List persons = allPersons.getResultList(); 114 | for(Person person:persons) 115 | em.remove(person); 116 | System.out.println(persons.size() + " persons deleted!"); 117 | tx.commit(); 118 | em.close(); 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/jpa/spring/domain/Factory.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.jpa.spring.domain; 2 | 3 | public interface Factory { 4 | 5 | public Person createPerson(); 6 | } 7 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/jpa/spring/domain/Person.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.jpa.spring.domain; 2 | 3 | import java.util.Date; 4 | 5 | import javax.persistence.Column; 6 | import javax.persistence.Entity; 7 | import javax.persistence.Id; 8 | import javax.persistence.Table; 9 | import javax.persistence.Temporal; 10 | import javax.persistence.TemporalType; 11 | 12 | @Entity(name="Person") 13 | @Table(name="PERSONS_2") 14 | public class Person { 15 | @Id 16 | @Column(name="ID") 17 | private int id; 18 | 19 | @Column(name="FIRSTNAME") 20 | private String firstName; 21 | 22 | @Column(name="LASTNAME") 23 | private String lastName; 24 | 25 | @Column(name="DATE_OF_BIRTH") 26 | @Temporal(TemporalType.DATE) 27 | private Date dob; 28 | 29 | public Person() { 30 | } 31 | 32 | public Person(String firstName, String lastName) { 33 | this(0, firstName, lastName, null); 34 | } 35 | 36 | public Person(int id, String firstName, String lastName, Date dob) { 37 | this.id = id; 38 | this.firstName = firstName; 39 | this.lastName = lastName; 40 | this.dob = dob; 41 | } 42 | 43 | public Person(int id, String firstName, String lastName) { 44 | this(id, firstName, lastName, null); 45 | } 46 | 47 | public Person(int id) { 48 | this(id, null, null, null); 49 | } 50 | 51 | public int getId() { 52 | return id; 53 | } 54 | 55 | public void setId(int id) { 56 | this.id = id; 57 | } 58 | 59 | public String getFirstName() { 60 | return firstName; 61 | } 62 | 63 | public void setFirstName(String firstName) { 64 | this.firstName = firstName; 65 | } 66 | 67 | public String getLastName() { 68 | return lastName; 69 | } 70 | 71 | public void setLastName(String lastName) { 72 | this.lastName = lastName; 73 | } 74 | 75 | public Date getDob() { 76 | return dob; 77 | } 78 | 79 | public void setDob(Date dob) { 80 | this.dob = dob; 81 | } 82 | 83 | public java.sql.Date getDobAsSQlDate() { 84 | return new java.sql.Date(dob.getTime()); 85 | } 86 | 87 | @Override 88 | public int hashCode() { 89 | final int prime = 31; 90 | int result = 1; 91 | result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); 92 | result = prime * result + id; 93 | result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); 94 | return result; 95 | } 96 | 97 | @Override 98 | public boolean equals(Object obj) { 99 | if (this == obj) 100 | return true; 101 | if (obj == null) 102 | return false; 103 | if (getClass() != obj.getClass()) 104 | return false; 105 | Person other = (Person) obj; 106 | if (firstName == null) { 107 | if (other.firstName != null) 108 | return false; 109 | } else if (!firstName.equals(other.firstName)) 110 | return false; 111 | if (id != other.id) 112 | return false; 113 | if (lastName == null) { 114 | if (other.lastName != null) 115 | return false; 116 | } else if (!lastName.equals(other.lastName)) 117 | return false; 118 | return true; 119 | } 120 | 121 | @Override 122 | public String toString() { 123 | return "Person [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + "]"; 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/jpa/spring/domain/PersonFactory.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.jpa.spring.domain; 2 | 3 | import java.util.Calendar; 4 | import java.util.Date; 5 | import java.util.Random; 6 | 7 | public class PersonFactory implements Factory{ 8 | private static PersonFactory personFactory = new PersonFactory(); 9 | private static Random random = new Random(); 10 | 11 | private static String[] firstnames = { "Ali", "Ayse", "Bahar", "Cem", "Demet", "Eylem", "Faruk", "Fatma", "Ganime", 12 | "Haydar", "Halil", "Ismail", "Jale", "Kemal", "Leman", "Mustafa", "Nedim", "Nilufer", "Selim", "Selman", 13 | "Sevda", "Tarik", "Teoman", "Yeliz", "Zuhal" }; 14 | private static String[] lastnames = { "Arabaci", "Aslan", "Batur", "Bulut", "Ceviz", "Karli", "Lale", "Ozturk", 15 | "Pasa", "Sari", "Serim", "Telli", "Torbaci", "Yazar", "Zafer" }; 16 | 17 | private PersonFactory() {} 18 | 19 | public static PersonFactory getInstance() { 20 | return personFactory; 21 | } 22 | 23 | @Override 24 | public Person createPerson() { 25 | Person person = new Person(); 26 | person.setId(createId()); 27 | person.setFirstName(createFirstName()); 28 | person.setLastName(createLastName()); 29 | person.setDob(createDob()); 30 | return person; 31 | } 32 | 33 | private int createId() { 34 | int randomInt = random.nextInt(); 35 | if (randomInt < 0) 36 | randomInt = -randomInt; 37 | return randomInt; 38 | } 39 | 40 | private String createFirstName() { 41 | int randomInt = random.nextInt(25); 42 | return firstnames[randomInt]; 43 | } 44 | 45 | private String createLastName() { 46 | int randomInt = random.nextInt(15); 47 | return lastnames[randomInt]; 48 | } 49 | 50 | private Date createDob() { 51 | Calendar calendar = Calendar.getInstance(); 52 | calendar.set(1950 + random.nextInt(60), random.nextInt(11), random.nextInt(30)); 53 | return calendar.getTime(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/jpa/spring/domain/ex/NoSuchPersonException.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.jpa.spring.domain.ex; 2 | 3 | public class NoSuchPersonException extends Exception{ 4 | private static String message = "No such person found! Id: "; 5 | 6 | public NoSuchPersonException(int id) { 7 | super(message + id); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/jpa/spring/resources/jpa.properties: -------------------------------------------------------------------------------- 1 | # JPA Properties 2 | 3 | #Persistence Unit Name 4 | unitName=ch03_2 5 | 6 | # Provider 7 | javax.persistence.provider=org.eclipse.persistence.jpa.PersistenceProvider 8 | #javax.persistence.provider=org.hibernate.jpa.HibernatePersistenceProvider 9 | # 10 | 11 | # Please activate the suitable set of properties of your DB choice 12 | 13 | #JavaDB (Derby) 14 | #javax.persistence.jdbc.url=jdbc:derby://localhost:1527/JPA;create=true 15 | #javax.persistence.jdbc.user=app 16 | #javax.persistence.jdbc.password=password 17 | #javax.persistence.jdbc.driver=org.apache.derby.jdbc.ClientDriver 18 | #javax.persistence.schema-generation.database.action=drop-and-create 19 | # none, create, drop-and-create, drop 20 | 21 | #MySQL 22 | javax.persistence.jdbc.url=jdbc:mysql://localhost/JPA 23 | javax.persistence.jdbc.user=root 24 | javax.persistence.jdbc.password=password 25 | javax.persistence.jdbc.driver=com.mysql.cj.jdbc.Driver 26 | javax.persistence.schema-generation.database.action=drop-and-create 27 | 28 | ##PostgreSQL 29 | #javax.persistence.jdbc.url=jdbc:postgresql://localhost:5432/JPA 30 | #javax.persistence.jdbc.user=postgres 31 | #javax.persistence.jdbc.password=password 32 | #javax.persistence.jdbc.driver=org.postgresql.Driver 33 | #javax.persistence.schema-generation.database.action=create 34 | 35 | 36 | #https://wiki.eclipse.org/EclipseLink/Examples/JPA/Logging 37 | #eclipselink.logging.logger=DefaultLogger 38 | #eclipselink.logging.level.sql=FINE 39 | #eclipselink.logging.level=INFO 40 | #eclipselink.logging.thread=true 41 | #eclipselink.logging.session 42 | #eclipselink.logging.timestamp 43 | #eclipselink.logging.exceptions 44 | # 45 | 46 | #eclipselink.weaving.lazy=true 47 | #eclipselink.weaving=false 48 | #eclipselink.weaving.lazy=false 49 | #weaving.eager=true 50 | #eclipselink.weaving.lazy=true 51 | #eclipselink.weaving.eager=true 52 | # 53 | #hibernate.show_sql=true 54 | #hibernate.format_sql=true 55 | #hibernate.enableLazyInitialization=true 56 | #hibernate.dialect=DerbyDialect 57 | #hibernate.enable_lazy_load_no_trans=false 58 | #hibernate.ejb.use_class_enhancer=true 59 | 60 | #Oracle XE 61 | #javax.persistence.jdbc.url=jdbc:oracle:thin:@localhost:1521:xe 62 | #javax.persistence.jdbc.user=jpa 63 | #javax.persistence.jdbc.password=password 64 | #javax.persistence.jdbc.driver=oracle.jdbc.driver.OracleDriver 65 | 66 | #HSQLDB 67 | #javax.persistence.jdbc.url=jdbc:hsqldb:hsql:JpaDB 68 | #javax.persistence.jdbc.user=SA 69 | #javax.persistence.jdbc.password= 70 | #javax.persistence.jdbc.driver=org.hsqldb.jdbc.JDBCDriver 71 | 72 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/jpa/spring/uml/CD.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/src/org/javaturk/spring/data/ch03/jpa/spring/uml/CD.png -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/oodb/Db4oDaoTest.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.oodb; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import org.javaturk.spring.data.ch03.common.domain.*; 7 | import org.javaturk.spring.data.ch03.common.domain.Person; 8 | import org.javaturk.spring.data.ch03.common.domain.ex.NoSuchPersonException; 9 | 10 | public class Db4oDaoTest { 11 | private PersonDb4oDAO dao = new PersonDb4oDAO(); 12 | private Factory personFactory; 13 | 14 | public static void main(String[] args) throws NoSuchPersonException { 15 | Db4oDaoTest test = new Db4oDaoTest(); 16 | test.run(); 17 | } 18 | 19 | public void run() throws NoSuchPersonException { 20 | // int id = 1; 21 | // Person person2 = new Person(id, "Ali", "Ozmen", new Date()); 22 | // dao.savePerson(person2); 23 | 24 | // Person personRetrieved = null; 25 | // try { 26 | // personRetrieved = dao.retrievePerson(id); 27 | // System.out.println(personRetrieved); 28 | // } catch (NoSuchPersonException e) { 29 | // System.out.println("Person does not exists!"); 30 | // System.out.println(e.getMessage()); 31 | // } 32 | 33 | // dao.deletePerson(personRetrieved); 34 | 35 | // savePersons(100); 36 | 37 | // List persons = dao.retrieveAllPersons(); 38 | // for(Person person : persons) 39 | // System.out.println(person); 40 | 41 | // int id = 83920280; 42 | // Person person = dao.retrievePerson(id); 43 | // System.out.println("Before update: " + person); 44 | // person.setDob(new Date(2_000_000_000)); 45 | // dao.updatePersonDOB(person); 46 | // person = dao.retrievePerson(id); 47 | // System.out.println("After update: " + person); 48 | 49 | // dao.deleteAllPersons(); 50 | } 51 | 52 | /* 53 | * Utility method to populate the database 54 | * 55 | * @param n Number of the persons to be created. 56 | */ 57 | public void savePersons(int n) { 58 | System.out.println("\nSaving " + n + " persons to DB"); 59 | PersonFactory personFactory = PersonFactory.getInstance(); 60 | for (int i = 0; i < n; i++) { 61 | Person p = personFactory.createPerson(); 62 | dao.savePerson(p); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/oodb/PersonDb4oDAO.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.oodb; 2 | 3 | import java.util.Date; 4 | import java.util.Iterator; 5 | import java.util.List; 6 | 7 | import org.javaturk.spring.data.ch03.common.dao.PersonDao; 8 | import org.javaturk.spring.data.ch03.common.domain.Person; 9 | import org.javaturk.spring.data.ch03.common.domain.PersonFactory; 10 | import org.javaturk.spring.data.ch03.common.domain.ex.NoSuchPersonException; 11 | 12 | import com.db4o.Db4oEmbedded; 13 | import com.db4o.ObjectContainer; 14 | import com.db4o.ObjectSet; 15 | 16 | public class PersonDb4oDAO implements PersonDao { 17 | 18 | final static String DB4OFILENAME = System.getProperty("user.home") + "/ch01.db4o"; 19 | private static ObjectContainer db; 20 | private static PersonFactory factory; 21 | 22 | public PersonDb4oDAO() { 23 | db = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), DB4OFILENAME); 24 | factory = PersonFactory.getInstance(); 25 | } 26 | 27 | @Override 28 | public void savePerson(Person person) { 29 | System.out.println("Saving person:" + person); 30 | db.store(person); 31 | System.out.println("Person saved!"); 32 | } 33 | 34 | @Override 35 | public int retrievePersonCount() { 36 | ObjectSet persons = db.query(Person.class); 37 | int size = persons.size(); 38 | return size; 39 | } 40 | 41 | @Override 42 | public Person retrievePerson(int id) throws NoSuchPersonException{ 43 | System.out.println("Retrieving the person with id = " + id); 44 | Person prototype = new Person(id); 45 | ObjectSet result = db.queryByExample(prototype); 46 | int personCount = result.size(); 47 | if(personCount > 0){ 48 | Person personRetrieved = result.get(0); 49 | return personRetrieved; 50 | } 51 | else 52 | throw new NoSuchPersonException(id); 53 | } 54 | 55 | @Override 56 | public List retrieveAllPersons() { 57 | System.out.println("\nRetrieving all persons by query."); 58 | ObjectSet persons = db.query(Person.class); 59 | System.out.println(persons.size() + " persons retrieved."); 60 | return persons; 61 | } 62 | 63 | @Override 64 | public void updatePersonDOB(Person person) { 65 | System.out.println("Updating a person's date of birth:" + person); 66 | Person prototype = new Person(person.getId()); 67 | ObjectSet persons = db.queryByExample(prototype); 68 | 69 | int updateCount = persons.size(); 70 | if(updateCount == 0){ 71 | System.out.println("No such person with id = " + person.getId()); 72 | System.out.println("No person updated!"); 73 | } 74 | else{ 75 | Person personToUpdate = persons.get(0); 76 | personToUpdate.setDob(person.getDob()); 77 | db.store(personToUpdate); 78 | System.out.println("Person updated!"); 79 | } 80 | } 81 | 82 | @Override 83 | public void deletePerson(Person person) { 84 | System.out.println("Deleting a person:" + person); 85 | Person prototype = new Person(person.getId(), person.getFirstName(), person.getLastName()); 86 | ObjectSet persons = db.queryByExample(prototype); 87 | int updateCount = persons.size(); 88 | if(updateCount == 0){ 89 | System.out.println("No such person with id = " + person.getId()); 90 | System.out.println("No person deleted!"); 91 | } 92 | else{ 93 | Person personToDelete = persons.get(0); 94 | db.delete(personToDelete); 95 | System.out.println("Person deleted!"); 96 | } 97 | } 98 | 99 | @Override 100 | public void deleteAllPersons() { 101 | System.out.println("Deleting all persons."); 102 | ObjectSet persons = db.query(Person.class); 103 | int updateCount = persons.size(); 104 | Iterator iterator = persons.iterator(); 105 | while(iterator.hasNext()){ 106 | Person person = iterator.next(); 107 | db.delete(person); 108 | } 109 | System.out.println(updateCount + " persons deleted!"); 110 | } 111 | 112 | public void closeDB(){ 113 | db.close(); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/spring/localContainerEMFBean/LocalContainerEntityManagerFactoryBeanTest.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.spring.localContainerEMFBean; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import org.javaturk.spring.data.ch03.spring.localEMFBean.dao.*; 7 | import org.javaturk.spring.data.ch03.jpa.spring.domain.Factory; 8 | import org.javaturk.spring.data.ch03.jpa.spring.domain.Person; 9 | import org.javaturk.spring.data.ch03.jpa.spring.domain.ex.NoSuchPersonException; 10 | import org.javaturk.spring.data.ch03.spring.localContainerEMFBean.conf.*; 11 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 12 | import org.springframework.context.annotation.Import; 13 | 14 | @Import({ AppConfig.class, JPAConfig.class }) 15 | public class LocalContainerEntityManagerFactoryBeanTest { 16 | private static AnnotationConfigApplicationContext context; 17 | private PersonDao dao; 18 | 19 | public static void main(String[] args) throws NoSuchPersonException { 20 | context = new AnnotationConfigApplicationContext(LocalContainerEntityManagerFactoryBeanTest.class); 21 | LocalContainerEntityManagerFactoryBeanTest test = context.getBean(LocalContainerEntityManagerFactoryBeanTest.class); 22 | test.dao = context.getBean(PersonDao.class); 23 | test.run(); 24 | } 25 | 26 | public void run() throws NoSuchPersonException { 27 | System.out.println("Number of person: " + dao.retrievePersonCount()); 28 | 29 | // int id = 8; 30 | // Person person2 = new Person(id, "Ali", "Ozmen", new Date()); 31 | // dao.savePerson(person2); 32 | // 33 | // Person personRetrieved = null; 34 | // try { 35 | // personRetrieved = dao.retrievePerson(id); 36 | // System.out.println(personRetrieved); 37 | // } catch (NoSuchPersonException e) { 38 | // System.out.println("Person does not exists!"); 39 | // System.out.println(e.getMessage()); 40 | // } 41 | 42 | // dao.deletePerson(personRetrieved); 43 | // 44 | // savePersons(100); 45 | // 46 | // List persons = dao.retrieveAllPersons(); 47 | // for(Person person : persons) 48 | // System.out.println(person); 49 | 50 | // int id = 317669; 51 | // Person person = dao.retrievePerson(id); 52 | // System.out.println("Before update: " + person); 53 | // person.setDob(new Date(2000000000)); 54 | // dao.updatePersonDOB(person); 55 | // person = dao.retrievePerson(id); 56 | // System.out.println("After update: " + person); 57 | 58 | // dao.deleteAllPersons(); 59 | } 60 | 61 | /* 62 | * Utility method to populate the database 63 | * 64 | * @param n Number of the persons to be created. 65 | */ 66 | public void savePersons(int n) { 67 | System.out.println("\nSaving " + n + " persons to DB"); 68 | Factory personFactory = context.getBean(Factory.class); 69 | for (int i = 0; i < n; i++) { 70 | Person p = personFactory.createPerson(); 71 | dao.savePerson(p); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/spring/localContainerEMFBean/conf/AppConfig.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.spring.localContainerEMFBean.conf; 2 | 3 | import org.javaturk.spring.data.ch03.jpa.spring.domain.Factory; 4 | import org.javaturk.spring.data.ch03.jpa.spring.domain.PersonFactory; 5 | import org.javaturk.spring.data.ch03.spring.localContainerEMFBean.dao.PersonJpaSpringLCEMFBDao; 6 | import org.javaturk.spring.data.ch03.spring.localEMFBean.dao.PersonDao; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.context.annotation.Scope; 10 | 11 | @Configuration 12 | public class AppConfig { 13 | 14 | @Bean 15 | @Scope("prototype") 16 | public PersonDao personJpaSpringLCEMFBDao() { 17 | System.out.println("Creating PersonJpaSpringLCEMFBDao"); 18 | return new PersonJpaSpringLCEMFBDao(); 19 | } 20 | 21 | @Bean 22 | @Scope("prototype") 23 | public Factory personFactory() { 24 | System.out.println("Creating PersonFactory"); 25 | return PersonFactory.getInstance(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/spring/localContainerEMFBean/conf/JPAConfig.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.spring.localContainerEMFBean.conf; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.SQLException; 6 | import java.util.*; 7 | 8 | import javax.annotation.PostConstruct; 9 | import javax.persistence.EntityManager; 10 | import javax.persistence.EntityManagerFactory; 11 | import javax.persistence.Persistence; 12 | import javax.sql.DataSource; 13 | 14 | import org.apache.commons.dbcp2.BasicDataSource; 15 | import org.eclipse.persistence.config.PersistenceUnitProperties; 16 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 17 | import org.javaturk.spring.data.ch02.jdbc.common.domain.PersonFactory; 18 | import org.springframework.beans.factory.annotation.Autowired; 19 | import org.springframework.beans.factory.annotation.Value; 20 | import org.springframework.context.annotation.Bean; 21 | import org.springframework.context.annotation.Configuration; 22 | import org.springframework.context.annotation.EnableLoadTimeWeaving; 23 | import org.springframework.context.annotation.EnableLoadTimeWeaving.AspectJWeaving; 24 | import org.springframework.context.annotation.PropertySource; 25 | import org.springframework.context.annotation.Scope; 26 | import org.springframework.core.env.Environment; 27 | import org.springframework.core.env.MapPropertySource; 28 | import org.springframework.orm.jpa.JpaVendorAdapter; 29 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; 30 | import org.springframework.orm.jpa.LocalEntityManagerFactoryBean; 31 | import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter; 32 | import org.springframework.core.env.*; 33 | 34 | @Configuration 35 | //@EnableLoadTimeWeaving(aspectjWeaving = AspectJWeaving.AUTODETECT) 36 | @PropertySource("org/javaturk/spring/data/ch03/spring/localContainerEMFBean/resources/jpa.properties") 37 | public class JPAConfig { 38 | 39 | @Value("${unitName}") 40 | private String unitName; 41 | 42 | @Value("${javax.persistence.provider}") 43 | private String provider; 44 | 45 | @Value("${eclipselink.weaving}") 46 | private String eclipselinkWeaving; 47 | 48 | @Value("${javax.persistence.jdbc.url}") 49 | private String url; 50 | 51 | @Value("${javax.persistence.jdbc.user}") 52 | private String user; 53 | 54 | @Value("${javax.persistence.jdbc.password}") 55 | private String password; 56 | 57 | @Value("${javax.persistence.jdbc.driver}") 58 | private String driver; 59 | 60 | @Value("${javax.persistence.schema-generation.database.action}") 61 | private String action; 62 | 63 | private Map properties; 64 | 65 | @Autowired 66 | private Environment env; 67 | 68 | @Bean 69 | public Map properties() { 70 | properties = new HashMap<>(); 71 | properties.put("javax.persistence.provider", provider); 72 | properties.put("javax.persistence.jdbc.url", url); 73 | properties.put("javax.persistence.jdbc.driver", driver); 74 | properties.put("javax.persistence.jdbc.user", user); 75 | properties.put("javax.persistence.jdbc.password", password); 76 | // properties.forEach((k, v) -> System.out.println(k + " " + v)); 77 | return properties; 78 | } 79 | 80 | @Bean 81 | @Scope("prototype") 82 | public DataSource dataSource1() { 83 | BasicDataSource basicDataSource = new BasicDataSource(); 84 | basicDataSource.setDriverClassName(env.getProperty("javax.persistence.jdbc.driver")); 85 | basicDataSource.setUrl(env.getProperty("javax.persistence.jdbc.url")); 86 | basicDataSource.setUsername(env.getProperty("javax.persistence.jdbc.user")); 87 | basicDataSource.setPassword(env.getProperty("javax.persistence.jdbc.password")); 88 | return basicDataSource; 89 | } 90 | 91 | @Bean 92 | @Scope("prototype") 93 | public DataSource dataSource2() { 94 | BasicDataSource basicDataSource = new BasicDataSource(); 95 | basicDataSource.setDriverClassName(driver); 96 | basicDataSource.setUrl(url); 97 | basicDataSource.setUsername(user); 98 | basicDataSource.setPassword(password); 99 | return basicDataSource; 100 | } 101 | 102 | @Bean 103 | public LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean() { 104 | System.out.println("Creating LocalContainerEntityManagerFactoryBean"); 105 | LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); 106 | em.setPersistenceUnitName(unitName); 107 | em.setJpaPropertyMap(properties); 108 | em.setDataSource(dataSource2()); 109 | 110 | JpaVendorAdapter vendorAdapter = new EclipseLinkJpaVendorAdapter(); 111 | em.setJpaVendorAdapter(vendorAdapter); 112 | 113 | Map jpaProperties = new HashMap<>(); 114 | jpaProperties.put(PersistenceUnitProperties.WEAVING, "false"); 115 | em.setJpaPropertyMap(jpaProperties); 116 | return em; 117 | } 118 | 119 | @PostConstruct 120 | public void listProperties() { 121 | System.out.format("******************************************************************************\n"); 122 | System.out.format("* %50s %20s \n", "Creating the persistence unit with following properties", "*"); 123 | System.out.format("* %-20s %-50s %4s \n", "Unit name:", unitName, "*"); 124 | System.out.format("* %-20s %-50s %4s \n", "Provider:", provider, "*"); 125 | System.out.format("* %-20s %-50s %4s \n", "URL:", url, "*"); 126 | System.out.format("* %-20s %-50s %4s \n", "Username:", user, "*"); 127 | System.out.format("* %-20s %-50s %4s \n", "Password:", password, "*"); 128 | System.out.format("* %-20s %-50s %4s \n", "Driver:", driver, "*"); 129 | System.out.format("* %-20s %-50s %4s \n", "Database action:", action, "*"); 130 | // System.out.format("* %-70s %5s \n", " * * * Other Properties * * * ", "*"); 131 | 132 | // Set keys = properties.keySet(); 133 | // for(Object key : keys) { 134 | // String stringKey = (String) key; 135 | // if(!stringKey.startsWith("javax")) 136 | // System.out.format("* %-50s %-20s %4s \n", stringKey + ":", properties.get(stringKey), "*"); 137 | // } 138 | System.out.format("******************************************************************************\n"); 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/spring/localContainerEMFBean/dao/PersonJpaSpringLCEMFBDao.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.spring.localContainerEMFBean.dao; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import javax.persistence.EntityManager; 7 | import javax.persistence.EntityManagerFactory; 8 | import javax.persistence.EntityTransaction; 9 | import javax.persistence.Query; 10 | 11 | import org.javaturk.spring.data.ch03.jpa.spring.domain.*; 12 | import org.javaturk.spring.data.ch03.jpa.spring.domain.ex.NoSuchPersonException; 13 | import org.javaturk.spring.data.ch03.spring.localEMFBean.dao.PersonDao; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | 16 | public class PersonJpaSpringLCEMFBDao implements PersonDao { 17 | 18 | @Autowired 19 | private EntityManagerFactory entityManagerFactory; 20 | 21 | @Override 22 | public void savePerson(Person person) { 23 | System.out.println("Saving person:" + person + "\n"); 24 | EntityManager em = entityManagerFactory.createEntityManager(); 25 | EntityTransaction tx = em.getTransaction(); 26 | tx.begin(); 27 | em.persist(person); 28 | tx.commit(); 29 | em.close(); 30 | 31 | System.out.println("Person saved!"); 32 | } 33 | 34 | @Override 35 | public Person retrievePerson(int id) throws NoSuchPersonException{ 36 | System.out.println("Retrieving the person with id = " + id); 37 | EntityManager em = entityManagerFactory.createEntityManager(); 38 | Person personRetrieved = em.find(Person.class, id); 39 | em.close(); 40 | if (personRetrieved == null) { 41 | System.out.println("No such person with id = " + id); 42 | throw new NoSuchPersonException(id); 43 | } else { 44 | return personRetrieved; 45 | } 46 | } 47 | 48 | @Override 49 | public int retrievePersonCount() { 50 | System.out.println("\nRetrieving all persons by query."); 51 | EntityManager em = entityManagerFactory.createEntityManager(); 52 | Query allPersons = em.createQuery("Select p from Person p"); 53 | List persons = allPersons.getResultList(); 54 | int size = persons.size(); 55 | em.close(); 56 | return size; 57 | } 58 | 59 | @Override 60 | public List retrieveAllPersons() { 61 | System.out.println("\nRetrieving all persons by query."); 62 | EntityManager em = entityManagerFactory.createEntityManager(); 63 | Query allPersons = em.createQuery("Select p from Person p"); 64 | List persons = allPersons.getResultList(); 65 | System.out.println(persons.size() + " objects:"); 66 | em.close(); 67 | return persons; 68 | } 69 | 70 | @Override 71 | public void updatePersonDOB(Person person) { 72 | System.out.println("\nUpdating a person's date of birth:" + person); 73 | EntityManager em = entityManagerFactory.createEntityManager(); 74 | EntityTransaction tx = em.getTransaction(); 75 | tx.begin(); 76 | Person updatedPerson = em.merge(person); 77 | if(updatedPerson == null){ 78 | System.out.println("No such person with id = " + person.getId()); 79 | System.out.println("No person updated!"); 80 | } 81 | else 82 | System.out.println("Person updated!"); 83 | tx.commit(); 84 | em.close(); 85 | 86 | } 87 | 88 | @Override 89 | public void deletePerson(Person person) { 90 | System.out.println("\nDeleting a person:" + person); 91 | EntityManager em = entityManagerFactory.createEntityManager(); 92 | EntityTransaction tx = em.getTransaction(); 93 | tx.begin(); 94 | Person personToDelete = em.find(Person.class, person.getId()); 95 | if(personToDelete == null){ 96 | System.out.println("No such person with id = " + person.getId()); 97 | System.out.println("No person deleted!"); 98 | } 99 | else{ 100 | em.remove(personToDelete); 101 | System.out.println("Person deleted!"); 102 | } 103 | tx.commit(); 104 | em.close(); 105 | } 106 | 107 | @Override 108 | public void deleteAllPersons() { 109 | System.out.println("\nDeleting all persons."); 110 | EntityManager em = entityManagerFactory.createEntityManager(); 111 | EntityTransaction tx = em.getTransaction(); 112 | tx.begin(); 113 | Query allPersons = em.createQuery("Select p from Person p"); 114 | List persons = allPersons.getResultList(); 115 | for(Person person:persons) 116 | em.remove(person); 117 | System.out.println(persons.size() + " persons deleted!"); 118 | tx.commit(); 119 | em.close(); 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/spring/localContainerEMFBean/resources/jpa.properties: -------------------------------------------------------------------------------- 1 | # JPA Properties 2 | 3 | #Persistence Unit Name 4 | unitName=ch03_4 5 | 6 | # Provider 7 | javax.persistence.provider=org.eclipse.persistence.jpa.PersistenceProvider 8 | eclipselinkWeaving=false 9 | #javax.persistence.provider=org.hibernate.jpa.HibernatePersistenceProvider 10 | # 11 | 12 | # Please activate the suitable set of properties of your DB choice 13 | 14 | #JavaDB (Derby) 15 | #javax.persistence.jdbc.url=jdbc:derby://localhost:1527/JPA;create=true 16 | #javax.persistence.jdbc.user=app 17 | #javax.persistence.jdbc.password=password 18 | #javax.persistence.jdbc.driver=org.apache.derby.jdbc.ClientDriver 19 | #javax.persistence.schema-generation.database.action=drop-and-create 20 | # none, create, drop-and-create, drop 21 | 22 | #MySQL 23 | javax.persistence.jdbc.url=jdbc:mysql://localhost/JPA 24 | javax.persistence.jdbc.user=root 25 | javax.persistence.jdbc.password=password 26 | javax.persistence.jdbc.driver=com.mysql.cj.jdbc.Driver 27 | javax.persistence.schema-generation.database.action=none 28 | 29 | ##PostgreSQL 30 | #javax.persistence.jdbc.url=jdbc:postgresql://localhost:5432/JPA 31 | #javax.persistence.jdbc.user=postgres 32 | #javax.persistence.jdbc.password=password 33 | #javax.persistence.jdbc.driver=org.postgresql.Driver 34 | #javax.persistence.schema-generation.database.action=create 35 | 36 | 37 | #https://wiki.eclipse.org/EclipseLink/Examples/JPA/Logging 38 | #eclipselink.logging.logger=DefaultLogger 39 | #eclipselink.logging.level.sql=FINE 40 | #eclipselink.logging.level=INFO 41 | #eclipselink.logging.thread=true 42 | #eclipselink.logging.session 43 | #eclipselink.logging.timestamp 44 | #eclipselink.logging.exceptions 45 | # 46 | 47 | #eclipselink.weaving.lazy=true 48 | #eclipselink.weaving=false 49 | #eclipselink.weaving.lazy=false 50 | #weaving.eager=true 51 | #eclipselink.weaving.lazy=true 52 | #eclipselink.weaving.eager=true 53 | # 54 | #hibernate.show_sql=true 55 | #hibernate.format_sql=true 56 | #hibernate.enableLazyInitialization=true 57 | #hibernate.dialect=DerbyDialect 58 | #hibernate.enable_lazy_load_no_trans=false 59 | #hibernate.ejb.use_class_enhancer=true 60 | 61 | #Oracle XE 62 | #javax.persistence.jdbc.url=jdbc:oracle:thin:@localhost:1521:xe 63 | #javax.persistence.jdbc.user=jpa 64 | #javax.persistence.jdbc.password=password 65 | #javax.persistence.jdbc.driver=oracle.jdbc.driver.OracleDriver 66 | 67 | #HSQLDB 68 | #javax.persistence.jdbc.url=jdbc:hsqldb:hsql:JpaDB 69 | #javax.persistence.jdbc.user=SA 70 | #javax.persistence.jdbc.password= 71 | #javax.persistence.jdbc.driver=org.hsqldb.jdbc.JDBCDriver 72 | 73 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/spring/localEMFBean/LocalEntityManagerFactoryBeanTest.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.spring.localEMFBean; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import org.javaturk.spring.data.ch03.spring.localEMFBean.dao.*; 7 | import org.javaturk.spring.data.ch03.jpa.spring.domain.Factory; 8 | import org.javaturk.spring.data.ch03.jpa.spring.domain.Person; 9 | import org.javaturk.spring.data.ch03.jpa.spring.domain.ex.NoSuchPersonException; 10 | import org.javaturk.spring.data.ch03.spring.localEMFBean.conf.*; 11 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 12 | import org.springframework.context.annotation.Import; 13 | 14 | @Import({ AppConfig.class, JPAConfig.class }) 15 | public class LocalEntityManagerFactoryBeanTest { 16 | private static AnnotationConfigApplicationContext context; 17 | private PersonDao dao; 18 | 19 | public static void main(String[] args) throws NoSuchPersonException { 20 | context = new AnnotationConfigApplicationContext(LocalEntityManagerFactoryBeanTest.class); 21 | LocalEntityManagerFactoryBeanTest test = context.getBean(LocalEntityManagerFactoryBeanTest.class); 22 | test.dao = context.getBean(PersonDao.class); 23 | test.run(); 24 | } 25 | 26 | public void run() throws NoSuchPersonException { 27 | System.out.println("Number of person: " + dao.retrievePersonCount()); 28 | 29 | int id = 7; 30 | Person person2 = new Person(id, "Ali", "Ozmen", new Date()); 31 | dao.savePerson(person2); 32 | 33 | Person personRetrieved = null; 34 | try { 35 | personRetrieved = dao.retrievePerson(id); 36 | System.out.println(personRetrieved); 37 | } catch (NoSuchPersonException e) { 38 | System.out.println("Person does not exists!"); 39 | System.out.println(e.getMessage()); 40 | } 41 | 42 | dao.deletePerson(personRetrieved); 43 | 44 | savePersons(100); 45 | 46 | List persons = dao.retrieveAllPersons(); 47 | for(Person person : persons) 48 | System.out.println(person); 49 | 50 | // int id = 1356865398; 51 | // Person person = dao.retrievePerson(id); 52 | // System.out.println("Before update: " + person); 53 | // person.setDob(new Date(2000000000)); 54 | // dao.updatePersonDOB(person); 55 | // person = dao.retrievePerson(id); 56 | // System.out.println("After update: " + person); 57 | 58 | // dao.deleteAllPersons(); 59 | } 60 | 61 | /* 62 | * Utility method to populate the database 63 | * 64 | * @param n Number of the persons to be created. 65 | */ 66 | public void savePersons(int n) { 67 | System.out.println("\nSaving " + n + " persons to DB"); 68 | Factory personFactory = context.getBean(Factory.class); 69 | for (int i = 0; i < n; i++) { 70 | Person p = personFactory.createPerson(); 71 | dao.savePerson(p); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/spring/localEMFBean/conf/AppConfig.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.spring.localEMFBean.conf; 2 | 3 | import org.javaturk.spring.data.ch03.jpa.spring.domain.Factory; 4 | import org.javaturk.spring.data.ch03.jpa.spring.domain.PersonFactory; 5 | import org.javaturk.spring.data.ch03.spring.localEMFBean.dao.PersonDao; 6 | import org.javaturk.spring.data.ch03.spring.localEMFBean.dao.PersonJpaSpringLEMFBDao; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.context.annotation.Scope; 10 | 11 | @Configuration 12 | public class AppConfig { 13 | 14 | @Bean 15 | @Scope("prototype") 16 | public PersonDao PersonJpaSpringDao() { 17 | System.out.println("Creating PersonJpaSpringLEMFBDao"); 18 | return new PersonJpaSpringLEMFBDao(); 19 | } 20 | 21 | @Bean 22 | @Scope("prototype") 23 | public Factory personFactory() { 24 | System.out.println("Creating PersonFactory"); 25 | return PersonFactory.getInstance(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/spring/localEMFBean/conf/JPAConfig.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.spring.localEMFBean.conf; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.SQLException; 6 | import java.util.*; 7 | 8 | import javax.annotation.PostConstruct; 9 | import javax.persistence.EntityManager; 10 | import javax.persistence.EntityManagerFactory; 11 | import javax.persistence.Persistence; 12 | import javax.sql.DataSource; 13 | 14 | import org.apache.commons.dbcp2.BasicDataSource; 15 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 16 | import org.javaturk.spring.data.ch02.jdbc.common.domain.PersonFactory; 17 | import org.springframework.beans.factory.annotation.Autowired; 18 | import org.springframework.beans.factory.annotation.Value; 19 | import org.springframework.context.annotation.Bean; 20 | import org.springframework.context.annotation.Configuration; 21 | import org.springframework.context.annotation.PropertySource; 22 | import org.springframework.context.annotation.Scope; 23 | import org.springframework.core.env.Environment; 24 | import org.springframework.core.env.MapPropertySource; 25 | import org.springframework.orm.jpa.LocalEntityManagerFactoryBean; 26 | import org.springframework.core.env.*; 27 | 28 | @Configuration 29 | @PropertySource("org/javaturk/spring/data/ch03/spring/localEMFBean/resources/jpa.properties") 30 | public class JPAConfig { 31 | 32 | @Value("${unitName}") 33 | private String unitName; 34 | 35 | @Value("${javax.persistence.provider}") 36 | private String provider; 37 | 38 | @Value("${javax.persistence.jdbc.url}") 39 | private String url; 40 | 41 | @Value("${javax.persistence.jdbc.user}") 42 | private String user; 43 | 44 | @Value("${javax.persistence.jdbc.password}") 45 | private String password; 46 | 47 | @Value("${javax.persistence.jdbc.driver}") 48 | private String driver; 49 | 50 | @Value("${javax.persistence.schema-generation.database.action}") 51 | private String action; 52 | 53 | private Map properties; 54 | 55 | @Bean 56 | public Map properties() { 57 | properties = new HashMap<>(); 58 | properties.put("javax.persistence.provider", provider); 59 | properties.put("javax.persistence.jdbc.url", url); 60 | properties.put("javax.persistence.jdbc.driver", driver); 61 | properties.put("javax.persistence.jdbc.user", user); 62 | properties.put("javax.persistence.jdbc.password", password); 63 | // properties.forEach((k, v) -> System.out.println(k + " " + v)); 64 | return properties; 65 | } 66 | 67 | @Bean 68 | public LocalEntityManagerFactoryBean localEntityManagerFactoryBean(){ 69 | System.out.println("Creating LocalEntityManagerFactoryBean"); 70 | LocalEntityManagerFactoryBean localEntityManagerFactoryBean = new LocalEntityManagerFactoryBean(); 71 | localEntityManagerFactoryBean.setPersistenceUnitName(unitName); 72 | localEntityManagerFactoryBean.setJpaPropertyMap(properties); 73 | // DataSource ds = localEntityManagerFactoryBean.getDataSource(); 74 | // System.out.println("DS:" + ds); 75 | return localEntityManagerFactoryBean; 76 | } 77 | 78 | @PostConstruct 79 | public void listProperties() { 80 | System.out.format("******************************************************************************\n"); 81 | System.out.format("* %50s %20s \n", "Creating the persistence unit with following properties", "*"); 82 | System.out.format("* %-20s %-50s %4s \n", "Unit name:", unitName, "*"); 83 | System.out.format("* %-20s %-50s %4s \n", "Provider:", provider, "*"); 84 | System.out.format("* %-20s %-50s %4s \n", "URL:", url, "*"); 85 | System.out.format("* %-20s %-50s %4s \n", "Username:", user, "*"); 86 | System.out.format("* %-20s %-50s %4s \n", "Password:", password, "*"); 87 | System.out.format("* %-20s %-50s %4s \n", "Driver:", driver, "*"); 88 | System.out.format("* %-20s %-50s %4s \n", "Database action:", action, "*"); 89 | // System.out.format("* %-70s %5s \n", " * * * Other Properties * * * ", "*"); 90 | 91 | // Set keys = properties.keySet(); 92 | // for(Object key : keys) { 93 | // String stringKey = (String) key; 94 | // if(!stringKey.startsWith("javax")) 95 | // System.out.format("* %-50s %-20s %4s \n", stringKey + ":", properties.get(stringKey), "*"); 96 | // } 97 | System.out.format("******************************************************************************\n"); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/spring/localEMFBean/dao/PersonDao.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.spring.localEMFBean.dao; 2 | 3 | import java.util.List; 4 | 5 | import org.javaturk.spring.data.ch03.jpa.spring.domain.Person; 6 | import org.javaturk.spring.data.ch03.jpa.spring.domain.ex.NoSuchPersonException; 7 | 8 | 9 | public interface PersonDao { 10 | 11 | public void savePerson(Person person); 12 | 13 | public int retrievePersonCount(); 14 | 15 | public Person retrievePerson(int id) throws NoSuchPersonException; 16 | 17 | public List retrieveAllPersons(); 18 | 19 | public void updatePersonDOB(Person person); 20 | 21 | public void deletePerson(Person person); 22 | 23 | public void deleteAllPersons(); 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/spring/localEMFBean/dao/PersonJpaSpringLEMFBDao.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch03.spring.localEMFBean.dao; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import javax.persistence.EntityManager; 7 | import javax.persistence.EntityManagerFactory; 8 | import javax.persistence.EntityTransaction; 9 | import javax.persistence.Query; 10 | 11 | import org.javaturk.spring.data.ch03.jpa.spring.domain.*; 12 | import org.javaturk.spring.data.ch03.jpa.spring.domain.ex.NoSuchPersonException; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | 15 | public class PersonJpaSpringLEMFBDao implements PersonDao { 16 | 17 | @Autowired 18 | private EntityManagerFactory entityManagerFactory; 19 | 20 | @Override 21 | public void savePerson(Person person) { 22 | System.out.println("Saving person:" + person + "\n"); 23 | EntityManager em = entityManagerFactory.createEntityManager(); 24 | EntityTransaction tx = em.getTransaction(); 25 | tx.begin(); 26 | em.persist(person); 27 | tx.commit(); 28 | em.close(); 29 | 30 | System.out.println("Person saved!"); 31 | } 32 | 33 | @Override 34 | public Person retrievePerson(int id) throws NoSuchPersonException{ 35 | System.out.println("Retrieving the person with id = " + id); 36 | EntityManager em = entityManagerFactory.createEntityManager(); 37 | Person personRetrieved = em.find(Person.class, id); 38 | em.close(); 39 | if (personRetrieved == null) { 40 | System.out.println("No such person with id = " + id); 41 | throw new NoSuchPersonException(id); 42 | } else { 43 | return personRetrieved; 44 | } 45 | } 46 | 47 | @Override 48 | public int retrievePersonCount() { 49 | System.out.println("\nRetrieving all persons by query."); 50 | EntityManager em = entityManagerFactory.createEntityManager(); 51 | Query allPersons = em.createQuery("Select p from Person p"); 52 | List persons = allPersons.getResultList(); 53 | int size = persons.size(); 54 | em.close(); 55 | return size; 56 | } 57 | 58 | @Override 59 | public List retrieveAllPersons() { 60 | System.out.println("\nRetrieving all persons by query."); 61 | EntityManager em = entityManagerFactory.createEntityManager(); 62 | Query allPersons = em.createQuery("Select p from Person p"); 63 | List persons = allPersons.getResultList(); 64 | System.out.println(persons.size() + " objects:"); 65 | em.close(); 66 | return persons; 67 | } 68 | 69 | @Override 70 | public void updatePersonDOB(Person person) { 71 | System.out.println("\nUpdating a person's date of birth:" + person); 72 | EntityManager em = entityManagerFactory.createEntityManager(); 73 | EntityTransaction tx = em.getTransaction(); 74 | tx.begin(); 75 | Person updatedPerson = em.merge(person); 76 | if(updatedPerson == null){ 77 | System.out.println("No such person with id = " + person.getId()); 78 | System.out.println("No person updated!"); 79 | } 80 | else 81 | System.out.println("Person updated!"); 82 | tx.commit(); 83 | em.close(); 84 | 85 | } 86 | 87 | @Override 88 | public void deletePerson(Person person) { 89 | System.out.println("\nDeleting a person:" + person); 90 | EntityManager em = entityManagerFactory.createEntityManager(); 91 | EntityTransaction tx = em.getTransaction(); 92 | tx.begin(); 93 | Person personToDelete = em.find(Person.class, person.getId()); 94 | if(personToDelete == null){ 95 | System.out.println("No such person with id = " + person.getId()); 96 | System.out.println("No person deleted!"); 97 | } 98 | else{ 99 | em.remove(personToDelete); 100 | System.out.println("Person deleted!"); 101 | } 102 | tx.commit(); 103 | em.close(); 104 | } 105 | 106 | @Override 107 | public void deleteAllPersons() { 108 | System.out.println("\nDeleting all persons."); 109 | EntityManager em = entityManagerFactory.createEntityManager(); 110 | EntityTransaction tx = em.getTransaction(); 111 | tx.begin(); 112 | Query allPersons = em.createQuery("Select p from Person p"); 113 | List persons = allPersons.getResultList(); 114 | for(Person person:persons) 115 | em.remove(person); 116 | System.out.println(persons.size() + " persons deleted!"); 117 | tx.commit(); 118 | em.close(); 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch03/spring/localEMFBean/resources/jpa.properties: -------------------------------------------------------------------------------- 1 | # JPA Properties 2 | 3 | #Persistence Unit Name 4 | unitName=ch03_3 5 | 6 | # Provider 7 | javax.persistence.provider=org.eclipse.persistence.jpa.PersistenceProvider 8 | #javax.persistence.provider=org.hibernate.jpa.HibernatePersistenceProvider 9 | # 10 | 11 | # Please activate the suitable set of properties of your DB choice 12 | 13 | #JavaDB (Derby) 14 | #javax.persistence.jdbc.url=jdbc:derby://localhost:1527/JPA;create=true 15 | #javax.persistence.jdbc.user=app 16 | #javax.persistence.jdbc.password=password 17 | #javax.persistence.jdbc.driver=org.apache.derby.jdbc.ClientDriver 18 | #javax.persistence.schema-generation.database.action=drop-and-create 19 | # none, create, drop-and-create, drop 20 | 21 | #MySQL 22 | javax.persistence.jdbc.url=jdbc:mysql://localhost/JPA 23 | javax.persistence.jdbc.user=root 24 | javax.persistence.jdbc.password=password 25 | javax.persistence.jdbc.driver=com.mysql.cj.jdbc.Driver 26 | javax.persistence.schema-generation.database.action=none 27 | 28 | ##PostgreSQL 29 | #javax.persistence.jdbc.url=jdbc:postgresql://localhost:5432/JPA 30 | #javax.persistence.jdbc.user=postgres 31 | #javax.persistence.jdbc.password=password 32 | #javax.persistence.jdbc.driver=org.postgresql.Driver 33 | #javax.persistence.schema-generation.database.action=create 34 | 35 | 36 | #https://wiki.eclipse.org/EclipseLink/Examples/JPA/Logging 37 | #eclipselink.logging.logger=DefaultLogger 38 | #eclipselink.logging.level.sql=FINE 39 | #eclipselink.logging.level=INFO 40 | #eclipselink.logging.thread=true 41 | #eclipselink.logging.session 42 | #eclipselink.logging.timestamp 43 | #eclipselink.logging.exceptions 44 | # 45 | 46 | #eclipselink.weaving.lazy=true 47 | #eclipselink.weaving=false 48 | #eclipselink.weaving.lazy=false 49 | #weaving.eager=true 50 | #eclipselink.weaving.lazy=true 51 | #eclipselink.weaving.eager=true 52 | # 53 | #hibernate.show_sql=true 54 | #hibernate.format_sql=true 55 | #hibernate.enableLazyInitialization=true 56 | #hibernate.dialect=DerbyDialect 57 | #hibernate.enable_lazy_load_no_trans=false 58 | #hibernate.ejb.use_class_enhancer=true 59 | 60 | #Oracle XE 61 | #javax.persistence.jdbc.url=jdbc:oracle:thin:@localhost:1521:xe 62 | #javax.persistence.jdbc.user=jpa 63 | #javax.persistence.jdbc.password=password 64 | #javax.persistence.jdbc.driver=oracle.jdbc.driver.OracleDriver 65 | 66 | #HSQLDB 67 | #javax.persistence.jdbc.url=jdbc:hsqldb:hsql:JpaDB 68 | #javax.persistence.jdbc.user=SA 69 | #javax.persistence.jdbc.password= 70 | #javax.persistence.jdbc.driver=org.hsqldb.jdbc.JDBCDriver 71 | 72 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch04/repository/jdbc/basic/JdbcTest.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch04.repository.jdbc.basic; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import org.javaturk.spring.data.ch02.jdbc.basic.dao.PersonJdbcDAO; 7 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 8 | import org.javaturk.spring.data.ch02.jdbc.common.domain.PersonFactory; 9 | import org.javaturk.spring.data.ch02.jdbc.common.domain.ex.NoSuchPersonException; 10 | 11 | public class JdbcTest { 12 | private static PersonJdbcDAO dao = new PersonJdbcDAO(); 13 | 14 | public static void main(String[] args) throws NoSuchPersonException { 15 | System.out.println("Number of person: " + dao.retrievePersonCount()); 16 | 17 | // int id = 2; 18 | // Person person2 = new Person(id, "Ali", "Ozmen", new Date()); 19 | // dao.savePerson(person2); 20 | // 21 | // Person personRetrieved = null; 22 | // try { 23 | // personRetrieved = dao.retrievePerson(id); 24 | // System.out.println(personRetrieved); 25 | // } catch (NoSuchPersonException e) { 26 | // System.out.println("Person does not exists!"); 27 | // System.out.println(e.getMessage()); 28 | // } 29 | 30 | // dao.deletePerson(personRetrieved); 31 | 32 | // savePersons(100); 33 | 34 | // List persons = dao.retrieveAllPersons(); 35 | // for(Person person : persons) 36 | // System.out.println(person); 37 | 38 | // int id = 2; 39 | // Person person = dao.retrievePerson(id); 40 | // System.out.println("Before update: " + person); 41 | // person.setDob(new Date(2000000000)); 42 | // dao.updatePersonDOB(person); 43 | // person = dao.retrievePerson(id); 44 | // System.out.println("After update: " + person); 45 | 46 | // dao.deleteAllPersons(); 47 | } 48 | 49 | /** 50 | * Utility method to populate the database 51 | * 52 | * @param n Number of the persons to be created. 53 | */ 54 | public static void savePersons(int n) { 55 | System.out.println("\nSaving " + n + " persons to DB"); 56 | PersonFactory personFactory = PersonFactory.getInstance(); 57 | for (int i = 0; i < n; i++) { 58 | Person p = personFactory.createPerson(); 59 | dao.savePerson(p); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch04/repository/jdbc/basic/dao/PersonJdbcDAO.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch04.repository.jdbc.basic.dao; 2 | 3 | import java.sql.Connection; 4 | import java.sql.PreparedStatement; 5 | import java.sql.ResultSet; 6 | import java.sql.SQLException; 7 | import java.util.ArrayList; 8 | import java.util.Date; 9 | import java.util.List; 10 | 11 | import org.javaturk.spring.data.ch02.jdbc.basic.util.JdbcUtil; 12 | import org.javaturk.spring.data.ch02.jdbc.common.data.PersonDAO; 13 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 14 | import org.javaturk.spring.data.ch02.jdbc.common.domain.PersonFactory; 15 | import org.javaturk.spring.data.ch02.jdbc.common.domain.ex.NoSuchPersonException; 16 | import org.springframework.stereotype.Repository; 17 | 18 | @Repository 19 | public class PersonJdbcDAO implements PersonDAO { 20 | private static final String SAVE_PERSON_QUERY = "INSERT INTO PERSONS VALUES(?,?,?,?)"; 21 | private static final String COUNT_QUERY = "SELECT COUNT(*) AS COUNT FROM PERSONS"; 22 | private static final String RETRIEVE_PERSON_QUERY = "SELECT * FROM PERSONS WHERE ID = ?"; 23 | private static final String RETRIEVE_ALL_PERSONS_QUERY = "SELECT * FROM PERSONS"; 24 | private static final String UPDATE_PERSONDOB_QUERY = "UPDATE PERSONS SET DATEOFBIRTH = ? WHERE ID = ?"; 25 | private static final String DELETE_PERSON_QUERY = "DELETE FROM PERSONS WHERE ID = ?"; 26 | private static final String DELETE_ALL_PERSONS_QUERY = "DELETE FROM PERSONS"; 27 | 28 | @Override 29 | public void savePerson(Person person) { 30 | System.out.println("\nSaving person:" + person); 31 | Connection conn = getConnection(); 32 | PreparedStatement stmt = null; 33 | try { 34 | stmt = conn.prepareStatement(SAVE_PERSON_QUERY); 35 | stmt.setInt(1, person.getId()); 36 | stmt.setString(2, person.getFirstName()); 37 | stmt.setString(3, person.getLastName()); 38 | stmt.setDate(4, person.getDobAsSQlDate()); 39 | int updateCount = stmt.executeUpdate(); 40 | if (updateCount != 1) 41 | System.out.println("Problem with saving the person."); 42 | else 43 | System.out.println("Person saved!"); 44 | } catch (SQLException e) { 45 | System.out.println("Problem with statement: " + e.getMessage()); 46 | e.printStackTrace(); 47 | } finally { 48 | returnConnection(conn); 49 | } 50 | } 51 | 52 | @Override 53 | public int retrievePersonCount() { 54 | int personCount = -1; 55 | Connection conn = getConnection(); 56 | try { 57 | PreparedStatement stmt = conn.prepareStatement(COUNT_QUERY); 58 | ResultSet rs = stmt.executeQuery(); 59 | while(rs.next()){ 60 | personCount = rs.getInt("COUNT"); 61 | } 62 | } catch (SQLException e) { 63 | System.out.println("Problem with statement: " + e.getMessage()); 64 | e.printStackTrace(); 65 | } 66 | finally{ 67 | returnConnection(conn); 68 | } 69 | return personCount; 70 | } 71 | 72 | @Override 73 | public Person retrievePerson(int id) throws NoSuchPersonException { 74 | System.out.println("\nRetrieving the person with id = " + id); 75 | Person personRetrieved = null; 76 | Connection conn = getConnection(); 77 | try { 78 | PreparedStatement stmt = conn.prepareStatement(RETRIEVE_PERSON_QUERY); 79 | stmt.setInt(1, id); 80 | ResultSet rs = stmt.executeQuery(); 81 | while(rs.next()){ 82 | String firstName = rs.getString("FIRSTNAME"); 83 | String lastName = rs.getString("LASTNAME"); 84 | Date dob = rs.getDate("DATEOFBIRTH"); 85 | personRetrieved = new Person(id, firstName, lastName, dob); 86 | } 87 | if(personRetrieved == null) 88 | // System.out.println("No such person with id = " + id); 89 | throw new NoSuchPersonException(id); 90 | } catch (SQLException e) { 91 | System.out.println("Problem with statement: " + e.getMessage()); 92 | e.printStackTrace(); 93 | } 94 | finally{ 95 | returnConnection(conn); 96 | } 97 | return personRetrieved; 98 | } 99 | 100 | @Override 101 | public List retrieveAllPersons() { 102 | System.out.println("\nRetrieving all of the persons."); 103 | List persons = new ArrayList(); 104 | Connection conn = getConnection(); 105 | try { 106 | PreparedStatement stmt = conn.prepareStatement(RETRIEVE_ALL_PERSONS_QUERY); 107 | ResultSet rs = stmt.executeQuery(); 108 | while (rs.next()) { 109 | int id = rs.getInt("ID"); 110 | String firstName = rs.getString("FIRSTNAME"); 111 | String lastName = rs.getString("LASTNAME"); 112 | Date dob = rs.getDate("DATEOFBIRTH"); 113 | Person personRetrieved = new Person(id, firstName, lastName, dob); 114 | persons.add(personRetrieved); 115 | } 116 | } catch (SQLException e) { 117 | System.out.println("Problem with statement: " + e.getMessage()); 118 | e.printStackTrace(); 119 | } finally { 120 | returnConnection(conn); 121 | } 122 | System.out.println(persons.size() + " persons retrieved."); 123 | return persons; 124 | } 125 | 126 | @Override 127 | public void updatePersonDOB(Person person) { 128 | System.out.println("\nUpdating a person's date of birth:" + person); 129 | Connection conn = getConnection(); 130 | PreparedStatement stmt = null; 131 | try { 132 | stmt = conn.prepareStatement(UPDATE_PERSONDOB_QUERY); 133 | stmt.setDate(1, person.getDobAsSQlDate()); 134 | stmt.setInt(2, person.getId()); 135 | int updateCount = stmt.executeUpdate(); 136 | if (updateCount != 1) { 137 | System.out.println("No such person with id = " + person.getId()); 138 | System.out.println("No person updated!"); 139 | } else 140 | System.out.println("Person updated!"); 141 | } catch (SQLException e) { 142 | System.out.println("Problem with statement: " + e.getMessage()); 143 | e.printStackTrace(); 144 | } finally { 145 | returnConnection(conn); 146 | } 147 | } 148 | 149 | @Override 150 | public void deletePerson(Person person) { 151 | System.out.println("\nDeleting a person:" + person); 152 | Connection conn = getConnection(); 153 | try { 154 | PreparedStatement stmt = conn.prepareStatement(DELETE_PERSON_QUERY); 155 | stmt.setInt(1, person.getId()); 156 | int updateCount = stmt.executeUpdate(); 157 | if (updateCount != 1) { 158 | System.out.println("No such person with id = " + person.getId()); 159 | System.out.println("No person deleted!."); 160 | } else 161 | System.out.println("Person deleted!"); 162 | } catch (SQLException e) { 163 | System.out.println("Problem with statement: " + e.getMessage()); 164 | e.printStackTrace(); 165 | } finally { 166 | returnConnection(conn); 167 | } 168 | } 169 | 170 | @Override 171 | public void deleteAllPersons() { 172 | System.out.println("\nDeleting all persons."); 173 | Connection conn = getConnection(); 174 | try { 175 | PreparedStatement stmt = conn.prepareStatement(DELETE_ALL_PERSONS_QUERY); 176 | int updateCount = stmt.executeUpdate(); 177 | System.out.println(updateCount + " persons deleted!"); 178 | } catch (SQLException e) { 179 | System.out.println("Problem with statement: " + e.getMessage()); 180 | e.printStackTrace(); 181 | } finally { 182 | returnConnection(conn); 183 | } 184 | } 185 | 186 | private Connection getConnection() { 187 | return JdbcUtil.getConnection(); 188 | } 189 | 190 | private void returnConnection(Connection conn) { 191 | try { 192 | // Closing connection would close statements too. 193 | conn.close(); 194 | } catch (SQLException e) { 195 | System.out.println("Problem with closing the connection: " + e.getMessage()); 196 | e.printStackTrace(); 197 | } 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch04/repository/jdbc/basic/uml/CD1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/src/org/javaturk/spring/data/ch04/repository/jdbc/basic/uml/CD1.png -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch04/repository/jdbc/basic/uml/CD2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaturk/SpringData/a8983b0bb742cfff1bbb0c7eb3c2c87356da65a1/src/org/javaturk/spring/data/ch04/repository/jdbc/basic/uml/CD2.png -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch04/repository/jdbc/basic/util/JdbcUtil.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch04.repository.jdbc.basic.util; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.io.FileReader; 5 | import java.io.IOException; 6 | import java.sql.Connection; 7 | import java.sql.DriverManager; 8 | import java.sql.SQLException; 9 | import java.util.Properties; 10 | 11 | import javax.sql.DataSource; 12 | 13 | import org.apache.commons.dbcp2.BasicDataSource; 14 | import org.springframework.context.annotation.Bean; 15 | 16 | public class JdbcUtil { 17 | private static Properties settings = new Properties(); 18 | private static String fileName = "/Users/akin/Java/Eclipse/202003/workspace/Spring WS/Spring Data/src/org/javaturk/spring/data/ch02/jdbc/common/resources/jdbc.properties"; 19 | 20 | private static String url; 21 | private static String ip; 22 | private static String port; 23 | private static String username; 24 | private static String password; 25 | private static String driver; 26 | 27 | private static BasicDataSource basicDataSource; 28 | 29 | static { 30 | FileReader in = null; 31 | try { 32 | in = new FileReader(fileName); 33 | } catch (FileNotFoundException e1) { 34 | System.out.println("File is not found: " + fileName); 35 | e1.printStackTrace(); 36 | } 37 | try { 38 | settings.load(in); 39 | } catch (IOException e) { 40 | System.out.println("Problem with IO: " + e.getMessage()); 41 | e.printStackTrace(); 42 | } 43 | 44 | // Use this line to list all loaded properties. 45 | // settings.list(System.out); 46 | 47 | url = settings.getProperty("url"); 48 | username = settings.getProperty("username"); 49 | password = settings.getProperty("password"); 50 | driver = settings.getProperty("driver"); 51 | 52 | listProperties(); 53 | 54 | // Create a data source 55 | basicDataSource = new BasicDataSource(); 56 | basicDataSource.setDriverClassName(driver); 57 | basicDataSource.setUrl(url); 58 | basicDataSource.setUsername(username); 59 | basicDataSource.setPassword(password); 60 | } 61 | 62 | // public static Connection getConnection() { 63 | // Connection connection = null; 64 | // try { 65 | // Class.forName(driver); 66 | // connection = DriverManager.getConnection(url, username, password); 67 | // } catch (ClassNotFoundException e) { 68 | // System.out.println(driver + " is not found: " + e.getMessage()); 69 | // e.printStackTrace(); 70 | // } catch (SQLException e) { 71 | // System.out.println("In JDBCUtil, problem with getting a connection: " + e.getMessage()); 72 | // e.printStackTrace(); 73 | // } 74 | // return connection; 75 | // } 76 | 77 | public static Connection getConnection() { 78 | Connection connection = null; 79 | try { 80 | connection = basicDataSource.getConnection(); 81 | } catch (SQLException e) { 82 | System.out.println("In JDBCUtil, problem with getting a connection: " + e.getMessage()); 83 | e.printStackTrace(); 84 | } 85 | return connection; 86 | } 87 | 88 | public static void listProperties() { 89 | System.err.format("\n******************************************************************************\n"); 90 | System.err.format("* %50s %25s \n", "Creating the connection with following properties", "*"); 91 | System.err.format("* %-20s %-50s %4s \n", "URL:", url, "*"); 92 | System.err.format("* %-20s %-50s %4s \n", "Username:", username, "*"); 93 | System.err.format("* %-20s %-50s %4s \n", "Password:", password, "*"); 94 | System.err.format("* %-20s %-50s %4s \n", "Driver:", driver, "*"); 95 | System.err.format("******************************************************************************\n"); 96 | System.out.println(); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch04/repository/jdbc/jdbcTemplate/person/JdbcTemplateRespositoryTest.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch04.repository.jdbc.jdbcTemplate.person; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import org.javaturk.spring.data.ch02.jdbc.common.data.PersonDAO; 7 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Factory; 8 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 9 | import org.javaturk.spring.data.ch02.jdbc.common.domain.ex.NoSuchPersonException; 10 | import org.javaturk.spring.data.ch04.repository.jdbc.jdbcTemplate.person.conf.*; 11 | import org.javaturk.spring.data.ch04.repository.jdbc.jdbcTemplate.person.dao.PersonJdbcTemplateDAO; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 14 | import org.springframework.context.annotation.ComponentScan; 15 | import org.springframework.context.annotation.Import; 16 | 17 | @Import({ AppConfig.class, JDBCConfig.class }) 18 | @ComponentScan("org.javaturk.spring.data.ch04.repository.jdbc.jdbcTemplate.person.dao") 19 | public class JdbcTemplateRespositoryTest { 20 | private static AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(JdbcTemplateRespositoryTest.class); 21 | 22 | // This should be before personFactory otherwise "Is there an unresolvable circular reference?" 23 | @Autowired 24 | PersonJdbcTemplateDAO dao; 25 | 26 | // @Autowired 27 | // Factory personFactory; 28 | 29 | public static void main(String[] args) { 30 | JdbcTemplateRespositoryTest test = context.getBean(JdbcTemplateRespositoryTest.class); 31 | test.run(); 32 | } 33 | 34 | public void run() { 35 | System.out.println("Number of person: " + dao.retrievePersonCount()); 36 | 37 | int id = 11; 38 | // Person person = new Person(id, "Ali", "Ozmen", new Date()); 39 | // dao.savePerson(person); 40 | 41 | // Person personRetrieved = null; 42 | // try { 43 | // personRetrieved = dao.retrievePerson(id); 44 | // System.out.println(personRetrieved); 45 | // } catch (NoSuchPersonException e) { 46 | // System.out.println("Person does not exists!"); 47 | // System.out.println(e.getMessage()); 48 | // } 49 | 50 | // dao.deletePerson(personRetrieved); 51 | 52 | // savePersons(100); 53 | 54 | // List persons = dao.retrieveAllPersons(); 55 | // System.out.println("There are " + persons.size() + " persons.\n"); 56 | // for(Person person : persons) 57 | // System.out.println(person); 58 | 59 | // int id = 1; 60 | // Person person = dao.retrievePerson(id); 61 | // System.out.println("Before update: " + person); 62 | // person.setDob(new Date(2000000000)); 63 | // dao.updatePersonDOB(person); 64 | // person = dao.retrievePerson(id); 65 | // System.out.println("After update: " + person); 66 | 67 | // dao.deleteAllPersons(); 68 | } 69 | 70 | /** 71 | * Utility method to populate the database 72 | * 73 | * @param n Number of the persons to be created. 74 | */ 75 | public void savePersons(int n) { 76 | System.out.println("\nSaving " + n + " persons to DB"); 77 | Factory personFactory = context.getBean(Factory.class); 78 | for (int i = 0; i < n; i++) { 79 | Person p = personFactory.createPerson(); 80 | dao.savePerson(p); 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch04/repository/jdbc/jdbcTemplate/person/conf/AppConfig.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch04.repository.jdbc.jdbcTemplate.person.conf; 2 | 3 | import javax.sql.DataSource; 4 | 5 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Factory; 6 | import org.javaturk.spring.data.ch02.jdbc.common.domain.PersonFactory; 7 | import org.javaturk.spring.data.ch04.repository.jdbc.jdbcTemplate.person.JdbcTemplateRespositoryTest; 8 | import org.javaturk.spring.data.ch04.repository.jdbc.jdbcTemplate.person.dao.PersonJdbcTemplateDAO; 9 | //import org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.domain.Person; 10 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.context.annotation.Bean; 13 | import org.springframework.context.annotation.Configuration; 14 | import org.springframework.context.annotation.Scope; 15 | 16 | @Configuration 17 | public class AppConfig { 18 | 19 | @Autowired 20 | private Factory personFactory; 21 | 22 | @Autowired 23 | private DataSource dataSource1; 24 | 25 | @Bean 26 | @Scope("prototype") 27 | public Person person() { 28 | return personFactory.createPerson(); 29 | } 30 | 31 | @Bean 32 | @Scope("singleton") 33 | public PersonFactory personFactory() { 34 | return PersonFactory.getInstance(); 35 | } 36 | 37 | // @Bean 38 | // @Scope("prototype") 39 | // public PersonJdbcTemplateDAO personJdbcTemplateDAO() { 40 | // System.out.println("Creating PersonJdbcTemplateDAO"); 41 | // return new PersonJdbcTemplateDAO(); 42 | // } 43 | } 44 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch04/repository/jdbc/jdbcTemplate/person/conf/JDBCConfig.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch04.repository.jdbc.jdbcTemplate.person.conf; 2 | 3 | import javax.annotation.PostConstruct; 4 | import javax.sql.DataSource; 5 | 6 | import org.apache.commons.dbcp2.BasicDataSource; 7 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 8 | import org.javaturk.spring.data.ch02.jdbc.common.domain.PersonFactory; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.beans.factory.annotation.Value; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.context.annotation.Configuration; 13 | import org.springframework.context.annotation.PropertySource; 14 | import org.springframework.context.annotation.Scope; 15 | import org.springframework.core.env.Environment; 16 | 17 | @Configuration 18 | @PropertySource("org/javaturk/spring/data/ch02/spring/jdbcTemplate/person/resources/jdbc.properties") 19 | public class JDBCConfig{ 20 | 21 | @Value("${jdbc.url}") 22 | private String url; 23 | 24 | @Value("${jdbc.username}") 25 | private String username; 26 | 27 | @Value("${jdbc.password}") 28 | private String password; 29 | 30 | @Value("${jdbc.driverClassName}") 31 | private String driver; 32 | 33 | @Autowired 34 | private Environment env; 35 | 36 | @Bean 37 | @Scope("prototype") 38 | public DataSource dataSource() { 39 | BasicDataSource basicDataSource = new BasicDataSource(); 40 | basicDataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); 41 | basicDataSource.setUrl(env.getProperty("jdbc.url")); 42 | basicDataSource.setUsername(env.getProperty("jdbc.username")); 43 | basicDataSource.setPassword(env.getProperty("jdbc.password")); 44 | return basicDataSource; 45 | } 46 | 47 | @PostConstruct 48 | public void listProperties() { 49 | System.err.format("\n******************************************************************************\n"); 50 | System.err.format("* %50s %25s \n", "Creating the connection with following properties", "*"); 51 | System.err.format("* %-20s %-50s %4s \n", "URL:", url, "*"); 52 | System.err.format("* %-20s %-50s %4s \n", "Username:", username, "*"); 53 | System.err.format("* %-20s %-50s %4s \n", "Password:", password, "*"); 54 | System.err.format("* %-20s %-50s %4s \n", "Driver:", driver, "*"); 55 | System.err.format("******************************************************************************\n"); 56 | System.out.println(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch04/repository/jdbc/jdbcTemplate/person/dao/PersonJdbcTemplateDAO.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch04.repository.jdbc.jdbcTemplate.person.dao; 2 | 3 | import java.util.List; 4 | 5 | import javax.sql.DataSource; 6 | 7 | import org.javaturk.spring.data.ch02.jdbc.common.data.PersonDAO; 8 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Factory; 9 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 10 | import org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.callback.PersonPreparedStatementIdAndDobSetter; 11 | import org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.callback.PersonPreparedStatementIdSetter; 12 | import org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.callback.PersonPreparedStatementSetter; 13 | import org.javaturk.spring.data.ch02.spring.jdbcTemplate.person.callback.PersonRowMapper; 14 | import org.javaturk.spring.data.ch02.jdbc.common.domain.ex.NoSuchPersonException; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.jdbc.core.JdbcTemplate; 17 | import org.springframework.stereotype.Repository; 18 | 19 | @Repository 20 | public class PersonJdbcTemplateDAO implements PersonDAO { 21 | private static final String SAVE_PERSON_QUERY = "INSERT INTO PERSONS VALUES(?,?,?,?)"; 22 | private static final String COUNT_QUERY = "SELECT COUNT(*) FROM PERSONS"; 23 | private static final String RETRIEVE_PERSON_QUERY = "SELECT * FROM PERSONS WHERE ID = ?"; 24 | private static final String RETRIEVE_ALL_PERSONS_QUERY = "SELECT * FROM PERSONS"; 25 | private static final String UPDATE_PERSONDOB_QUERY = "UPDATE PERSONS SET DATEOFBIRTH = ? WHERE ID = ?"; 26 | private static final String DELETE_PERSON_QUERY = "DELETE FROM PERSONS WHERE ID = ?"; 27 | private static final String DELETE_ALL_PERSONS_QUERY = "DELETE FROM PERSONS"; 28 | 29 | private JdbcTemplate jdbcTemplate; 30 | 31 | @Autowired 32 | PersonJdbcTemplateDAO(DataSource dataSource){ 33 | jdbcTemplate = new JdbcTemplate(dataSource);; 34 | } 35 | 36 | @Override 37 | public void savePerson(Person person) { 38 | System.out.println("\nSaving person:" + person); 39 | int count = jdbcTemplate.update(SAVE_PERSON_QUERY, new PersonPreparedStatementSetter(person)); 40 | if (count == 1) 41 | System.out.println("Person saved."); 42 | else 43 | System.out.println("Problem when saving Person."); 44 | } 45 | 46 | @Override 47 | public int retrievePersonCount() { 48 | return jdbcTemplate.queryForObject(COUNT_QUERY, Integer.class); 49 | } 50 | 51 | @Override 52 | public Person retrievePerson(int id) throws NoSuchPersonException { 53 | Person person = jdbcTemplate.queryForObject(RETRIEVE_PERSON_QUERY, new PersonRowMapper(), id); 54 | return person; 55 | } 56 | 57 | @Override 58 | public List retrieveAllPersons() { 59 | return (List) jdbcTemplate.query(RETRIEVE_ALL_PERSONS_QUERY, new PersonRowMapper()); 60 | } 61 | 62 | @Override 63 | public void updatePersonDOB(Person person) { 64 | int count = jdbcTemplate.update(UPDATE_PERSONDOB_QUERY, new PersonPreparedStatementIdAndDobSetter(person)); 65 | if (count == 1) 66 | System.out.println("Person has been updated."); 67 | else 68 | System.out.println("Problem when updating Person."); 69 | } 70 | 71 | @Override 72 | public void deletePerson(Person person) { 73 | jdbcTemplate.update(DELETE_PERSON_QUERY, new PersonPreparedStatementIdSetter(person)); 74 | } 75 | 76 | @Override 77 | public void deleteAllPersons() { 78 | int count = jdbcTemplate.update(DELETE_ALL_PERSONS_QUERY); 79 | System.out.println(count + " persons has been deleted."); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch04/repository/jpa/localContainerEMFBean/LocalContainerEntityManagerFactoryBeanRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch04.repository.jpa.localContainerEMFBean; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import org.javaturk.spring.data.ch03.spring.localEMFBean.dao.*; 7 | import org.javaturk.spring.data.ch04.repository.jpa.localContainerEMFBean.conf.*; 8 | import org.javaturk.spring.data.ch03.jpa.spring.domain.Factory; 9 | import org.javaturk.spring.data.ch03.jpa.spring.domain.Person; 10 | import org.javaturk.spring.data.ch03.jpa.spring.domain.ex.NoSuchPersonException; 11 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 12 | import org.springframework.context.annotation.ComponentScan; 13 | import org.springframework.context.annotation.Import; 14 | 15 | @Import({ AppConfig.class, JPAConfig.class }) 16 | @ComponentScan("org.javaturk.spring.data.ch04.repository.localContainerEMFBean.dao") 17 | public class LocalContainerEntityManagerFactoryBeanRepositoryTest { 18 | private static AnnotationConfigApplicationContext context; 19 | private PersonDao dao; 20 | 21 | public static void main(String[] args) throws NoSuchPersonException { 22 | context = new AnnotationConfigApplicationContext(LocalContainerEntityManagerFactoryBeanRepositoryTest.class); 23 | LocalContainerEntityManagerFactoryBeanRepositoryTest test = context.getBean(LocalContainerEntityManagerFactoryBeanRepositoryTest.class); 24 | test.dao = context.getBean(PersonDao.class); 25 | test.run(); 26 | } 27 | 28 | public void run() throws NoSuchPersonException { 29 | System.out.println("Number of person: " + dao.retrievePersonCount()); 30 | 31 | // int id = 8; 32 | // Person person2 = new Person(id, "Ali", "Ozmen", new Date()); 33 | // dao.savePerson(person2); 34 | // 35 | // Person personRetrieved = null; 36 | // try { 37 | // personRetrieved = dao.retrievePerson(id); 38 | // System.out.println(personRetrieved); 39 | // } catch (NoSuchPersonException e) { 40 | // System.out.println("Person does not exists!"); 41 | // System.out.println(e.getMessage()); 42 | // } 43 | 44 | // dao.deletePerson(personRetrieved); 45 | // 46 | // savePersons(100); 47 | // 48 | List persons = dao.retrieveAllPersons(); 49 | for(Person person : persons) 50 | System.out.println(person); 51 | 52 | // int id = 317669; 53 | // Person person = dao.retrievePerson(id); 54 | // System.out.println("Before update: " + person); 55 | // person.setDob(new Date(2000000000)); 56 | // dao.updatePersonDOB(person); 57 | // person = dao.retrievePerson(id); 58 | // System.out.println("After update: " + person); 59 | 60 | // dao.deleteAllPersons(); 61 | } 62 | 63 | /* 64 | * Utility method to populate the database 65 | * 66 | * @param n Number of the persons to be created. 67 | */ 68 | public void savePersons(int n) { 69 | System.out.println("\nSaving " + n + " persons to DB"); 70 | Factory personFactory = context.getBean(Factory.class); 71 | for (int i = 0; i < n; i++) { 72 | Person p = personFactory.createPerson(); 73 | dao.savePerson(p); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch04/repository/jpa/localContainerEMFBean/conf/AppConfig.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch04.repository.jpa.localContainerEMFBean.conf; 2 | 3 | import org.javaturk.spring.data.ch03.jpa.spring.domain.Factory; 4 | import org.javaturk.spring.data.ch03.jpa.spring.domain.PersonFactory; 5 | import org.javaturk.spring.data.ch03.spring.localContainerEMFBean.dao.PersonJpaSpringLCEMFBDao; 6 | import org.javaturk.spring.data.ch03.spring.localEMFBean.dao.PersonDao; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.context.annotation.Scope; 10 | 11 | @Configuration 12 | public class AppConfig { 13 | 14 | @Bean 15 | @Scope("prototype") 16 | public Factory personFactory() { 17 | System.out.println("Creating PersonFactory"); 18 | return PersonFactory.getInstance(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch04/repository/jpa/localContainerEMFBean/conf/JPAConfig.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch04.repository.jpa.localContainerEMFBean.conf; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.SQLException; 6 | import java.util.*; 7 | 8 | import javax.annotation.PostConstruct; 9 | import javax.persistence.EntityManager; 10 | import javax.persistence.EntityManagerFactory; 11 | import javax.persistence.Persistence; 12 | import javax.sql.DataSource; 13 | 14 | import org.apache.commons.dbcp2.BasicDataSource; 15 | import org.eclipse.persistence.config.PersistenceUnitProperties; 16 | import org.javaturk.spring.data.ch02.jdbc.common.domain.Person; 17 | import org.javaturk.spring.data.ch02.jdbc.common.domain.PersonFactory; 18 | import org.springframework.beans.factory.annotation.Autowired; 19 | import org.springframework.beans.factory.annotation.Value; 20 | import org.springframework.context.annotation.Bean; 21 | import org.springframework.context.annotation.Configuration; 22 | import org.springframework.context.annotation.EnableLoadTimeWeaving; 23 | import org.springframework.context.annotation.EnableLoadTimeWeaving.AspectJWeaving; 24 | import org.springframework.context.annotation.PropertySource; 25 | import org.springframework.context.annotation.Scope; 26 | import org.springframework.core.env.Environment; 27 | import org.springframework.core.env.MapPropertySource; 28 | import org.springframework.orm.jpa.JpaVendorAdapter; 29 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; 30 | import org.springframework.orm.jpa.LocalEntityManagerFactoryBean; 31 | import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter; 32 | import org.springframework.core.env.*; 33 | 34 | @Configuration 35 | //@EnableLoadTimeWeaving(aspectjWeaving = AspectJWeaving.AUTODETECT) 36 | @PropertySource("org/javaturk/spring/data/ch03/spring/localContainerEMFBean/resources/jpa.properties") 37 | public class JPAConfig { 38 | 39 | @Value("${unitName}") 40 | private String unitName; 41 | 42 | @Value("${javax.persistence.provider}") 43 | private String provider; 44 | 45 | @Value("${eclipselink.weaving}") 46 | private String eclipselinkWeaving; 47 | 48 | @Value("${javax.persistence.jdbc.url}") 49 | private String url; 50 | 51 | @Value("${javax.persistence.jdbc.user}") 52 | private String user; 53 | 54 | @Value("${javax.persistence.jdbc.password}") 55 | private String password; 56 | 57 | @Value("${javax.persistence.jdbc.driver}") 58 | private String driver; 59 | 60 | @Value("${javax.persistence.schema-generation.database.action}") 61 | private String action; 62 | 63 | private Map properties; 64 | 65 | @Autowired 66 | private Environment env; 67 | 68 | @Bean 69 | public Map properties() { 70 | properties = new HashMap<>(); 71 | properties.put("javax.persistence.provider", provider); 72 | properties.put("javax.persistence.jdbc.url", url); 73 | properties.put("javax.persistence.jdbc.driver", driver); 74 | properties.put("javax.persistence.jdbc.user", user); 75 | properties.put("javax.persistence.jdbc.password", password); 76 | // properties.forEach((k, v) -> System.out.println(k + " " + v)); 77 | return properties; 78 | } 79 | 80 | @Bean 81 | @Scope("prototype") 82 | public DataSource dataSource() { 83 | BasicDataSource basicDataSource = new BasicDataSource(); 84 | basicDataSource.setDriverClassName(env.getProperty("javax.persistence.jdbc.driver")); 85 | basicDataSource.setUrl(env.getProperty("javax.persistence.jdbc.url")); 86 | basicDataSource.setUsername(env.getProperty("javax.persistence.jdbc.user")); 87 | basicDataSource.setPassword(env.getProperty("javax.persistence.jdbc.password")); 88 | return basicDataSource; 89 | } 90 | 91 | // @Bean 92 | // @Scope("prototype") 93 | // public DataSource dataSource2() { 94 | // BasicDataSource basicDataSource = new BasicDataSource(); 95 | // basicDataSource.setDriverClassName(driver); 96 | // basicDataSource.setUrl(url); 97 | // basicDataSource.setUsername(user); 98 | // basicDataSource.setPassword(password); 99 | // return basicDataSource; 100 | // } 101 | 102 | @Bean 103 | public LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean() { 104 | System.out.println("Creating LocalContainerEntityManagerFactoryBean"); 105 | LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); 106 | em.setPersistenceUnitName(unitName); 107 | em.setJpaPropertyMap(properties); 108 | em.setDataSource(dataSource()); 109 | 110 | JpaVendorAdapter vendorAdapter = new EclipseLinkJpaVendorAdapter(); 111 | em.setJpaVendorAdapter(vendorAdapter); 112 | 113 | Map jpaProperties = new HashMap<>(); 114 | jpaProperties.put(PersistenceUnitProperties.WEAVING, "false"); 115 | em.setJpaPropertyMap(jpaProperties); 116 | return em; 117 | } 118 | 119 | @PostConstruct 120 | public void listProperties() { 121 | System.out.format("******************************************************************************\n"); 122 | System.out.format("* %50s %20s \n", "Creating the persistence unit with following properties", "*"); 123 | System.out.format("* %-20s %-50s %4s \n", "Unit name:", unitName, "*"); 124 | System.out.format("* %-20s %-50s %4s \n", "Provider:", provider, "*"); 125 | System.out.format("* %-20s %-50s %4s \n", "URL:", url, "*"); 126 | System.out.format("* %-20s %-50s %4s \n", "Username:", user, "*"); 127 | System.out.format("* %-20s %-50s %4s \n", "Password:", password, "*"); 128 | System.out.format("* %-20s %-50s %4s \n", "Driver:", driver, "*"); 129 | System.out.format("* %-20s %-50s %4s \n", "Database action:", action, "*"); 130 | // System.out.format("* %-70s %5s \n", " * * * Other Properties * * * ", "*"); 131 | 132 | // Set keys = properties.keySet(); 133 | // for(Object key : keys) { 134 | // String stringKey = (String) key; 135 | // if(!stringKey.startsWith("javax")) 136 | // System.out.format("* %-50s %-20s %4s \n", stringKey + ":", properties.get(stringKey), "*"); 137 | // } 138 | System.out.format("******************************************************************************\n"); 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/org/javaturk/spring/data/ch04/repository/jpa/localContainerEMFBean/dao/PersonJpaSpringLCEMFBDao.java: -------------------------------------------------------------------------------- 1 | package org.javaturk.spring.data.ch04.repository.jpa.localContainerEMFBean.dao; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import javax.persistence.EntityManager; 7 | import javax.persistence.EntityManagerFactory; 8 | import javax.persistence.EntityTransaction; 9 | import javax.persistence.Query; 10 | 11 | import org.javaturk.spring.data.ch03.jpa.spring.domain.*; 12 | import org.javaturk.spring.data.ch03.jpa.spring.domain.ex.NoSuchPersonException; 13 | import org.javaturk.spring.data.ch03.spring.localEMFBean.dao.PersonDao; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.stereotype.Repository; 16 | 17 | @Repository 18 | public class PersonJpaSpringLCEMFBDao implements PersonDao { 19 | 20 | @Autowired 21 | private EntityManagerFactory entityManagerFactory; 22 | 23 | @Override 24 | public void savePerson(Person person) { 25 | System.out.println("Saving person:" + person + "\n"); 26 | EntityManager em = entityManagerFactory.createEntityManager(); 27 | EntityTransaction tx = em.getTransaction(); 28 | tx.begin(); 29 | em.persist(person); 30 | tx.commit(); 31 | em.close(); 32 | 33 | System.out.println("Person saved!"); 34 | } 35 | 36 | @Override 37 | public Person retrievePerson(int id) throws NoSuchPersonException{ 38 | System.out.println("Retrieving the person with id = " + id); 39 | EntityManager em = entityManagerFactory.createEntityManager(); 40 | Person personRetrieved = em.find(Person.class, id); 41 | em.close(); 42 | if (personRetrieved == null) { 43 | System.out.println("No such person with id = " + id); 44 | throw new NoSuchPersonException(id); 45 | } else { 46 | return personRetrieved; 47 | } 48 | } 49 | 50 | @Override 51 | public int retrievePersonCount() { 52 | System.out.println("\nRetrieving all persons by query."); 53 | EntityManager em = entityManagerFactory.createEntityManager(); 54 | Query allPersons = em.createQuery("Select p from Person p"); 55 | List persons = allPersons.getResultList(); 56 | int size = persons.size(); 57 | em.close(); 58 | return size; 59 | } 60 | 61 | @Override 62 | public List retrieveAllPersons() { 63 | System.out.println("\nRetrieving all persons by query."); 64 | EntityManager em = entityManagerFactory.createEntityManager(); 65 | Query allPersons = em.createQuery("Select p from Person p"); 66 | List persons = allPersons.getResultList(); 67 | System.out.println(persons.size() + " objects:"); 68 | em.close(); 69 | return persons; 70 | } 71 | 72 | @Override 73 | public void updatePersonDOB(Person person) { 74 | System.out.println("\nUpdating a person's date of birth:" + person); 75 | EntityManager em = entityManagerFactory.createEntityManager(); 76 | EntityTransaction tx = em.getTransaction(); 77 | tx.begin(); 78 | Person updatedPerson = em.merge(person); 79 | if(updatedPerson == null){ 80 | System.out.println("No such person with id = " + person.getId()); 81 | System.out.println("No person updated!"); 82 | } 83 | else 84 | System.out.println("Person updated!"); 85 | tx.commit(); 86 | em.close(); 87 | 88 | } 89 | 90 | @Override 91 | public void deletePerson(Person person) { 92 | System.out.println("\nDeleting a person:" + person); 93 | EntityManager em = entityManagerFactory.createEntityManager(); 94 | EntityTransaction tx = em.getTransaction(); 95 | tx.begin(); 96 | Person personToDelete = em.find(Person.class, person.getId()); 97 | if(personToDelete == null){ 98 | System.out.println("No such person with id = " + person.getId()); 99 | System.out.println("No person deleted!"); 100 | } 101 | else{ 102 | em.remove(personToDelete); 103 | System.out.println("Person deleted!"); 104 | } 105 | tx.commit(); 106 | em.close(); 107 | } 108 | 109 | @Override 110 | public void deleteAllPersons() { 111 | System.out.println("\nDeleting all persons."); 112 | EntityManager em = entityManagerFactory.createEntityManager(); 113 | EntityTransaction tx = em.getTransaction(); 114 | tx.begin(); 115 | Query allPersons = em.createQuery("Select p from Person p"); 116 | List persons = allPersons.getResultList(); 117 | for(Person person:persons) 118 | em.remove(person); 119 | System.out.println(persons.size() + " persons deleted!"); 120 | tx.commit(); 121 | em.close(); 122 | } 123 | } 124 | --------------------------------------------------------------------------------