├── .gitignore
├── LICENSE
├── README.md
├── pom.xml
└── src
├── main
├── java
│ └── com
│ │ └── guitar
│ │ └── db
│ │ ├── config
│ │ └── JpaConfiguration.java
│ │ ├── model
│ │ ├── Location.java
│ │ ├── Manufacturer.java
│ │ ├── Model.java
│ │ └── ModelType.java
│ │ └── repository
│ │ ├── LocationRepository.java
│ │ ├── ManufacturerRepository.java
│ │ ├── ModelRepository.java
│ │ └── ModelTypeRepository.java
└── resources
│ ├── META-INF
│ ├── persistence.xml
│ └── spring
│ │ └── app-context.xml
│ └── h2
│ ├── data.sql
│ └── db.h2.db
└── test
├── java
└── com
│ └── guitar
│ └── db
│ ├── LocationPersistenceTests.java
│ ├── ManufacturerPersistenceTests.java
│ ├── ModelPersistenceTests.java
│ └── ModelTypePersistenceTests.java
└── resources
├── com
└── guitar
│ └── db
│ └── applicationTests-context.xml
└── log4j.properties
/.gitignore:
--------------------------------------------------------------------------------
1 | *.class
2 |
3 | # Mobile Tools for Java (J2ME)
4 | .mtj.tmp/
5 |
6 | # Package Files #
7 | *.jar
8 | *.war
9 | *.ear
10 |
11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
12 | hs_err_pid*
13 | /target/
14 | .classpath
15 | .project
16 | .settings/org.eclipse.jdt.core.prefs
17 | .settings/org.eclipse.jpt.core.prefs
18 | .settings/org.eclipse.m2e.core.prefs
19 | .settings/org.eclipse.wst.common.project.facet.core.prefs.xml
20 | .settings/org.eclipse.wst.common.project.facet.core.xml
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ps-guitar-db
2 | ============
3 |
4 | A Basic Spring JPA app with an H2 DB
5 |
6 | Prerequisites
7 | -------------
8 | You will need to following tools in order to work with this project and code
9 |
10 | * git (http://git-scm.com/)
11 | * JDK 1.8+ (http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)
12 | * Maven 3.x+ (http://maven.apache.org/)
13 | * An IDE of your choice. (Eclipse, IntelliJ, Spring STS, Netbeans, etc.)
14 |
15 | Getting Started
16 | ---------------
17 | To run this project locally, perform the following steps.
18 |
19 | * Clone project to your machine using git - "git clone https://github.com/dlbunker/ps-guitar-db.git"
20 | * Import the project into your IDE using the maven pom.xml. In spring STS suite this is done by importing an existing maven project
21 | * Run the JUnit tests in the src/test/java folder. If all pass you are good to go.
22 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 | com.guitar.db
7 | ps-guitar-db
8 | 1.0.0.SNAPSHOT
9 | jar
10 | Spring Data JPA Pluralsight Sample Project
11 |
12 |
13 | true
14 | 4.1.2.RELEASE
15 |
16 |
17 |
18 |
19 | org.hibernate
20 | hibernate-entitymanager
21 | 4.3.7.Final
22 |
23 |
24 | javax.validation
25 | validation-api
26 | 1.1.0.Final
27 |
28 |
29 | org.hibernate
30 | hibernate-validator
31 | 5.1.3.Final
32 |
33 |
34 |
35 | junit
36 | junit
37 | 4.9
38 | test
39 |
40 |
41 | org.springframework
42 | spring-test
43 | ${spring.framework.version}
44 | test
45 |
46 |
47 | org.springframework
48 | spring-context-support
49 | ${spring.framework.version}
50 |
51 |
52 | org.springframework
53 | spring-aop
54 | ${spring.framework.version}
55 |
56 |
57 | org.springframework
58 | spring-orm
59 | ${spring.framework.version}
60 |
61 |
62 | com.h2database
63 | h2
64 | 1.4.182
65 |
66 |
67 | log4j
68 | log4j
69 | 1.2.17
70 |
71 |
72 |
73 |
74 |
75 |
76 | org.apache.maven.plugins
77 | maven-compiler-plugin
78 |
79 | 1.8
80 | 1.8
81 |
82 |
83 |
84 |
85 |
86 |
--------------------------------------------------------------------------------
/src/main/java/com/guitar/db/config/JpaConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.guitar.db.config;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | import org.hibernate.dialect.H2Dialect;
7 | import org.springframework.beans.factory.annotation.Value;
8 | import org.springframework.context.annotation.Bean;
9 | import org.springframework.context.annotation.Configuration;
10 | import org.springframework.orm.jpa.JpaTransactionManager;
11 | import org.springframework.orm.jpa.JpaVendorAdapter;
12 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
13 | import org.springframework.orm.jpa.vendor.Database;
14 | import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
15 | import org.springframework.transaction.PlatformTransactionManager;
16 |
17 | @Configuration
18 | public class JpaConfiguration {
19 |
20 | @Value("#{dataSource}")
21 | private javax.sql.DataSource dataSource;
22 |
23 | @Bean
24 | public Map jpaProperties() {
25 | Map props = new HashMap();
26 | props.put("hibernate.dialect", H2Dialect.class.getName());
27 | // props.put("hibernate.cache.provider_class", HashtableCacheProvider.class.getName());
28 | return props;
29 | }
30 |
31 | @Bean
32 | public JpaVendorAdapter jpaVendorAdapter() {
33 | HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
34 | hibernateJpaVendorAdapter.setShowSql(true);
35 | hibernateJpaVendorAdapter.setGenerateDdl(true);
36 | hibernateJpaVendorAdapter.setDatabase(Database.H2);
37 | return hibernateJpaVendorAdapter;
38 | }
39 |
40 | @Bean
41 | public PlatformTransactionManager transactionManager() {
42 | return new JpaTransactionManager( entityManagerFactory().getObject() );
43 | }
44 |
45 | @Bean
46 | public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
47 | LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
48 | lef.setDataSource(this.dataSource);
49 | lef.setJpaPropertyMap(this.jpaProperties());
50 | lef.setJpaVendorAdapter(this.jpaVendorAdapter());
51 | return lef;
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/src/main/java/com/guitar/db/model/Location.java:
--------------------------------------------------------------------------------
1 | package com.guitar.db.model;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import javax.persistence.CascadeType;
7 | import javax.persistence.Entity;
8 | import javax.persistence.GeneratedValue;
9 | import javax.persistence.GenerationType;
10 | import javax.persistence.Id;
11 | import javax.persistence.JoinColumn;
12 | import javax.persistence.OneToMany;
13 |
14 | @Entity
15 | public class Location {
16 | @Id
17 | @GeneratedValue(strategy=GenerationType.AUTO)
18 | private Long id;
19 |
20 | private String state;
21 | private String country;
22 |
23 | @OneToMany(cascade=CascadeType.ALL)
24 | @JoinColumn(name="LOCATION_ID")
25 | private List manufacturers = new ArrayList();
26 |
27 | public String getState() {
28 | return state;
29 | }
30 |
31 | public void setState(String state) {
32 | this.state = state;
33 | }
34 |
35 | public String getCountry() {
36 | return country;
37 | }
38 |
39 | public void setCountry(String country) {
40 | this.country = country;
41 | }
42 |
43 | public List getManufacturers() {
44 | return manufacturers;
45 | }
46 |
47 | public void setManufacturers(List manufacturers) {
48 | this.manufacturers = manufacturers;
49 | }
50 |
51 | public Long getId() {
52 | return id;
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/com/guitar/db/model/Manufacturer.java:
--------------------------------------------------------------------------------
1 | package com.guitar.db.model;
2 |
3 | import java.math.BigDecimal;
4 | import java.util.ArrayList;
5 | import java.util.Date;
6 | import java.util.List;
7 |
8 | import javax.persistence.CascadeType;
9 | import javax.persistence.Entity;
10 | import javax.persistence.GeneratedValue;
11 | import javax.persistence.GenerationType;
12 | import javax.persistence.Id;
13 | import javax.persistence.JoinColumn;
14 | import javax.persistence.ManyToOne;
15 | import javax.persistence.NamedNativeQuery;
16 | import javax.persistence.OneToMany;
17 |
18 | @Entity
19 | @NamedNativeQuery(name = "Manufacturer.getAllThatSellAcoustics",
20 | query = "SELECT m.id, m.name, m.foundedDate, m.averageYearlySales, m.location_id as headquarters_id "
21 | + "FROM Manufacturer m "
22 | + "LEFT JOIN Model mod ON (m.id = mod.manufacturer_id) "
23 | + "LEFT JOIN ModelType mt ON (mt.id = mod.modeltype_id) "
24 | + "WHERE (mt.name = ?)", resultClass = Manufacturer.class)
25 | public class Manufacturer {
26 | @Id
27 | @GeneratedValue(strategy=GenerationType.AUTO)
28 | private Long id;
29 |
30 | private String name;
31 | private Date foundedDate;
32 | private BigDecimal averageYearlySales;
33 |
34 | @OneToMany(cascade=CascadeType.ALL)
35 | @JoinColumn(name="MANUFACTURER_ID")
36 | private List models = new ArrayList();
37 |
38 | @ManyToOne
39 | private Location headquarters;
40 |
41 | public String getName() {
42 | return name;
43 | }
44 |
45 | public void setName(String name) {
46 | this.name = name;
47 | }
48 |
49 | public Date getFoundedDate() {
50 | return foundedDate;
51 | }
52 |
53 | public void setFoundedDate(Date foundedDate) {
54 | this.foundedDate = foundedDate;
55 | }
56 |
57 | public BigDecimal getAverageYearlySales() {
58 | return averageYearlySales;
59 | }
60 |
61 | public void setAverageYearlySales(BigDecimal averageYearlySales) {
62 | this.averageYearlySales = averageYearlySales;
63 | }
64 |
65 | public List getModels() {
66 | return models;
67 | }
68 |
69 | public void setModels(List models) {
70 | this.models = models;
71 | }
72 |
73 | public Location getHeadquarters() {
74 | return headquarters;
75 | }
76 |
77 | public void setHeadquarters(Location headquarters) {
78 | this.headquarters = headquarters;
79 | }
80 |
81 | public Long getId() {
82 | return id;
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/src/main/java/com/guitar/db/model/Model.java:
--------------------------------------------------------------------------------
1 | package com.guitar.db.model;
2 |
3 | import java.math.BigDecimal;
4 | import java.util.Date;
5 |
6 | import javax.persistence.Entity;
7 | import javax.persistence.GeneratedValue;
8 | import javax.persistence.GenerationType;
9 | import javax.persistence.Id;
10 | import javax.persistence.ManyToOne;
11 | import javax.persistence.NamedQuery;
12 |
13 | @Entity
14 | @NamedQuery(name="Model.findAllModelsByType", query="select m from Model m where m.modelType.name = :name")
15 | public class Model {
16 | @Id
17 | @GeneratedValue(strategy=GenerationType.AUTO)
18 | private Long id;
19 |
20 | private String name;
21 | private BigDecimal price;
22 | private int frets;
23 | private String woodType;
24 | private Date yearFirstMade;
25 |
26 | @ManyToOne
27 | private Manufacturer manufacturer;
28 |
29 | @ManyToOne
30 | private ModelType modelType;
31 |
32 | public String getName() {
33 | return name;
34 | }
35 |
36 | public void setName(String name) {
37 | this.name = name;
38 | }
39 |
40 | public BigDecimal getPrice() {
41 | return price;
42 | }
43 |
44 | public void setPrice(BigDecimal price) {
45 | this.price = price;
46 | }
47 |
48 | public int getFrets() {
49 | return frets;
50 | }
51 |
52 | public void setFrets(int frets) {
53 | this.frets = frets;
54 | }
55 |
56 | public String getWoodType() {
57 | return woodType;
58 | }
59 |
60 | public void setWoodType(String woodType) {
61 | this.woodType = woodType;
62 | }
63 |
64 | public Date getYearFirstMade() {
65 | return yearFirstMade;
66 | }
67 |
68 | public void setYearFirstMade(Date yearFirstMade) {
69 | this.yearFirstMade = yearFirstMade;
70 | }
71 |
72 | public Manufacturer getManufacturer() {
73 | return manufacturer;
74 | }
75 |
76 | public void setManufacturer(Manufacturer manufacturer) {
77 | this.manufacturer = manufacturer;
78 | }
79 |
80 | public ModelType getModelType() {
81 | return modelType;
82 | }
83 |
84 | public void setModelType(ModelType modelType) {
85 | this.modelType = modelType;
86 | }
87 |
88 | public Long getId() {
89 | return id;
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/src/main/java/com/guitar/db/model/ModelType.java:
--------------------------------------------------------------------------------
1 | package com.guitar.db.model;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import javax.persistence.CascadeType;
7 | import javax.persistence.Entity;
8 | import javax.persistence.GeneratedValue;
9 | import javax.persistence.GenerationType;
10 | import javax.persistence.Id;
11 | import javax.persistence.JoinColumn;
12 | import javax.persistence.OneToMany;
13 |
14 | @Entity
15 | public class ModelType {
16 | @Id
17 | @GeneratedValue(strategy=GenerationType.AUTO)
18 | private Long id;
19 |
20 | private String name;
21 |
22 | @OneToMany(cascade=CascadeType.ALL)
23 | @JoinColumn(name="MODELTYPE_ID")
24 | private List models = new ArrayList();
25 |
26 | public String getName() {
27 | return name;
28 | }
29 |
30 | public void setName(String name) {
31 | this.name = name;
32 | }
33 |
34 | public List getModels() {
35 | return models;
36 | }
37 |
38 | public void setModels(List models) {
39 | this.models = models;
40 | }
41 |
42 | public Long getId() {
43 | return id;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/com/guitar/db/repository/LocationRepository.java:
--------------------------------------------------------------------------------
1 | package com.guitar.db.repository;
2 |
3 | import java.util.List;
4 |
5 | import javax.persistence.EntityManager;
6 | import javax.persistence.PersistenceContext;
7 |
8 | import org.springframework.stereotype.Repository;
9 |
10 | import com.guitar.db.model.Location;
11 |
12 | @Repository
13 | public class LocationRepository {
14 | @PersistenceContext
15 | private EntityManager entityManager;
16 |
17 | /**
18 | * Create
19 | */
20 | public Location create(Location loc) {
21 | entityManager.persist(loc);
22 | entityManager.flush();
23 | return loc;
24 | }
25 |
26 | /**
27 | * Update
28 | */
29 | public Location update(Location loc) {
30 | loc = entityManager.merge(loc);
31 | entityManager.flush();
32 | return loc;
33 | }
34 |
35 | /**
36 | * Delete
37 | */
38 | public void delete(Location loc) {
39 | entityManager.remove(loc);
40 | entityManager.flush();
41 | }
42 |
43 | /**
44 | * Find
45 | */
46 | public Location find(Long id) {
47 | return entityManager.find(Location.class, id);
48 | }
49 |
50 | /**
51 | * Custom finder
52 | */
53 | public List getLocationByStateName(String name) {
54 | @SuppressWarnings("unchecked")
55 | List locs = entityManager
56 | .createQuery("select l from Location l where l.state like :state")
57 | .setParameter("state", name + "%").getResultList();
58 | return locs;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/main/java/com/guitar/db/repository/ManufacturerRepository.java:
--------------------------------------------------------------------------------
1 | package com.guitar.db.repository;
2 |
3 | import java.util.Date;
4 | import java.util.List;
5 |
6 | import javax.persistence.EntityManager;
7 | import javax.persistence.PersistenceContext;
8 |
9 | import org.springframework.stereotype.Repository;
10 |
11 | import com.guitar.db.model.Manufacturer;
12 |
13 | @Repository
14 | public class ManufacturerRepository {
15 | @PersistenceContext
16 | private EntityManager entityManager;
17 |
18 | /**
19 | * Create
20 | */
21 | public Manufacturer create(Manufacturer man) {
22 | entityManager.persist(man);
23 | entityManager.flush();
24 | return man;
25 | }
26 |
27 | /**
28 | * Update
29 | */
30 | public Manufacturer update(Manufacturer man) {
31 | man = entityManager.merge(man);
32 | entityManager.flush();
33 | return man;
34 | }
35 |
36 | /**
37 | * Delete
38 | */
39 | public void delete(Manufacturer man) {
40 | entityManager.remove(man);
41 | entityManager.flush();
42 | }
43 |
44 | /**
45 | * Find
46 | */
47 | public Manufacturer find(Long id) {
48 | return entityManager.find(Manufacturer.class, id);
49 | }
50 |
51 | /**
52 | * Custom finder
53 | */
54 | public List getManufacturersFoundedBeforeDate(Date date) {
55 | @SuppressWarnings("unchecked")
56 | List mans = entityManager
57 | .createQuery("select m from Manufacturer m where m.foundedDate < :date")
58 | .setParameter("date", date).getResultList();
59 | return mans;
60 | }
61 |
62 | /**
63 | * Custom finder
64 | */
65 | public Manufacturer getManufacturerByName(String name) {
66 | Manufacturer man = (Manufacturer)entityManager
67 | .createQuery("select m from Manufacturer m where m.name like :name")
68 | .setParameter("name", name + "%").getSingleResult();
69 | return man;
70 | }
71 |
72 | /**
73 | * Native Query finder
74 | */
75 | public List getManufacturersThatSellModelsOfType(String modelType) {
76 | @SuppressWarnings("unchecked")
77 | List mans = entityManager
78 | .createNamedQuery("Manufacturer.getAllThatSellAcoustics")
79 | .setParameter(1, modelType).getResultList();
80 | return mans;
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/src/main/java/com/guitar/db/repository/ModelRepository.java:
--------------------------------------------------------------------------------
1 | package com.guitar.db.repository;
2 |
3 | import java.math.BigDecimal;
4 | import java.util.List;
5 |
6 | import javax.persistence.EntityManager;
7 | import javax.persistence.PersistenceContext;
8 | import javax.persistence.criteria.CriteriaBuilder;
9 | import javax.persistence.criteria.CriteriaQuery;
10 |
11 | import org.springframework.stereotype.Repository;
12 |
13 | import com.guitar.db.model.Model;
14 |
15 | @Repository
16 | public class ModelRepository {
17 | @PersistenceContext
18 | private EntityManager entityManager;
19 |
20 | /**
21 | * Create
22 | */
23 | public Model create(Model mod) {
24 | entityManager.persist(mod);
25 | entityManager.flush();
26 | return mod;
27 | }
28 |
29 | /**
30 | * Update
31 | */
32 | public Model update(Model mod) {
33 | mod = entityManager.merge(mod);
34 | entityManager.flush();
35 | return mod;
36 | }
37 |
38 | /**
39 | * Delete
40 | */
41 | public void delete(Model mod) {
42 | entityManager.remove(mod);
43 | entityManager.flush();
44 | }
45 |
46 | /**
47 | * Find
48 | */
49 | public Model find(Long id) {
50 | return entityManager.find(Model.class, id);
51 | }
52 |
53 | /**
54 | * Custom finder
55 | */
56 | public List getModelsInPriceRange(BigDecimal lowest, BigDecimal highest) {
57 | @SuppressWarnings("unchecked")
58 | List mods = entityManager
59 | .createQuery("select m from Model m where m.price >= :lowest and m.price <= :highest")
60 | .setParameter("lowest", lowest)
61 | .setParameter("highest", highest).getResultList();
62 | return mods;
63 | }
64 |
65 | /**
66 | * Custom finder
67 | */
68 | public List getModelsByPriceRangeAndWoodType(BigDecimal lowest, BigDecimal highest, String wood) {
69 | @SuppressWarnings("unchecked")
70 | List mods = entityManager
71 | .createQuery("select m from Model m where m.price >= :lowest and m.price <= :highest and m.woodType like :wood")
72 | .setParameter("lowest", lowest)
73 | .setParameter("highest", highest)
74 | .setParameter("wood", "%" + wood + "%").getResultList();
75 | return mods;
76 | }
77 |
78 | /**
79 | * NamedQuery finder
80 | */
81 | public List getModelsByType(String modelType) {
82 | @SuppressWarnings("unchecked")
83 | List mods = entityManager
84 | .createNamedQuery("Model.findAllModelsByType")
85 | .setParameter("name", modelType).getResultList();
86 | return mods;
87 | }
88 |
89 | /**
90 | * Count
91 | */
92 | public Long getModelCount() {
93 | CriteriaBuilder qb = entityManager.getCriteriaBuilder();
94 | CriteriaQuery cq = qb.createQuery(Long.class);
95 | cq.select(qb.count(cq.from(Model.class)));
96 | return entityManager.createQuery(cq).getSingleResult();
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/src/main/java/com/guitar/db/repository/ModelTypeRepository.java:
--------------------------------------------------------------------------------
1 | package com.guitar.db.repository;
2 |
3 | import javax.persistence.EntityManager;
4 | import javax.persistence.PersistenceContext;
5 |
6 | import org.springframework.stereotype.Repository;
7 |
8 | import com.guitar.db.model.ModelType;
9 |
10 | @Repository
11 | public class ModelTypeRepository {
12 | @PersistenceContext
13 | private EntityManager entityManager;
14 |
15 | /**
16 | * Create
17 | */
18 | public ModelType create(ModelType mt) {
19 | entityManager.persist(mt);
20 | entityManager.flush();
21 | return mt;
22 | }
23 |
24 | /**
25 | * Update
26 | */
27 | public ModelType update(ModelType mt) {
28 | mt = entityManager.merge(mt);
29 | entityManager.flush();
30 | return mt;
31 | }
32 |
33 | /**
34 | * Delete
35 | */
36 | public void delete(ModelType mt) {
37 | entityManager.remove(mt);
38 | entityManager.flush();
39 | }
40 |
41 | /**
42 | * Find
43 | */
44 | public ModelType find(Long id) {
45 | return entityManager.find(ModelType.class, id);
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/resources/META-INF/persistence.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 | com.guitar.db.model.Location
10 | com.guitar.db.model.Manufacturer
11 | com.guitar.db.model.Model
12 | com.guitar.db.model.ModelType
13 | true
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/src/main/resources/META-INF/spring/app-context.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 | Example configuration to get you started.
11 |
12 |
13 |
14 |
15 |
16 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/src/main/resources/h2/data.sql:
--------------------------------------------------------------------------------
1 | delete model;
2 | delete modeltype;
3 | delete manufacturer;
4 | delete location;
5 |
6 | insert into location (id, country, state) values (1, 'United States', 'Alabama');
7 | insert into location (id, country, state) values (2, 'United States', 'Alaska');
8 | insert into location (id, country, state) values (3, 'United States', 'Arizona');
9 | insert into location (id, country, state) values (4, 'United States', 'Arkansas');
10 | insert into location (id, country, state) values (5, 'United States', 'California');
11 | insert into location (id, country, state) values (6, 'United States', 'Colorado');
12 | insert into location (id, country, state) values (7, 'United States', 'Connecticut');
13 | insert into location (id, country, state) values (8, 'United States', 'Delaware');
14 | insert into location (id, country, state) values (9, 'United States', 'Florida');
15 | insert into location (id, country, state) values (10, 'United States', 'Georgia');
16 | insert into location (id, country, state) values (11, 'United States', 'Hawaii');
17 | insert into location (id, country, state) values (12, 'United States', 'Idaho');
18 | insert into location (id, country, state) values (13, 'United States', 'Illinois');
19 | insert into location (id, country, state) values (14, 'United States', 'Indiana');
20 | insert into location (id, country, state) values (15, 'United States', 'Iowa');
21 | insert into location (id, country, state) values (16, 'United States', 'Kansas');
22 | insert into location (id, country, state) values (17, 'United States', 'Kentucky');
23 | insert into location (id, country, state) values (18, 'United States', 'Louisiana');
24 | insert into location (id, country, state) values (19, 'United States', 'Maine');
25 | insert into location (id, country, state) values (20, 'United States', 'Maryland');
26 | insert into location (id, country, state) values (21, 'United States', 'Massachusetts');
27 | insert into location (id, country, state) values (22, 'United States', 'Michigan');
28 | insert into location (id, country, state) values (23, 'United States', 'Minnesota');
29 | insert into location (id, country, state) values (24, 'United States', 'Mississippi');
30 | insert into location (id, country, state) values (25, 'United States', 'Missouri');
31 | insert into location (id, country, state) values (26, 'United States', 'Montana');
32 | insert into location (id, country, state) values (27, 'United States', 'Nebraska');
33 | insert into location (id, country, state) values (28, 'United States', 'Nevada');
34 | insert into location (id, country, state) values (29, 'United States', 'New Hampshire');
35 | insert into location (id, country, state) values (30, 'United States', 'New Jersey');
36 | insert into location (id, country, state) values (31, 'United States', 'New Mexico');
37 | insert into location (id, country, state) values (32, 'United States', 'New York');
38 | insert into location (id, country, state) values (33, 'United States', 'North Carolina');
39 | insert into location (id, country, state) values (34, 'United States', 'North Dakota');
40 | insert into location (id, country, state) values (35, 'United States', 'Ohio');
41 | insert into location (id, country, state) values (36, 'United States', 'Oklahoma');
42 | insert into location (id, country, state) values (37, 'United States', 'Oregon');
43 | insert into location (id, country, state) values (38, 'United States', 'Pennsylvania');
44 | insert into location (id, country, state) values (39, 'United States', 'Rhode Island');
45 | insert into location (id, country, state) values (40, 'United States', 'South Carolina');
46 | insert into location (id, country, state) values (41, 'United States', 'South Dakota');
47 | insert into location (id, country, state) values (42, 'United States', 'Tennessee');
48 | insert into location (id, country, state) values (43, 'United States', 'Texas');
49 | insert into location (id, country, state) values (44, 'United States', 'Utah');
50 | insert into location (id, country, state) values (45, 'United States', 'Vermont');
51 | insert into location (id, country, state) values (46, 'United States', 'Virginia');
52 | insert into location (id, country, state) values (47, 'United States', 'Washington');
53 | insert into location (id, country, state) values (48, 'United States', 'West Virginia');
54 | insert into location (id, country, state) values (49, 'United States', 'Wisconsin');
55 | insert into location (id, country, state) values (50, 'United States', 'Wyoming');
56 |
57 | insert into manufacturer (id, name, location_id, averageYearlySales, foundedDate) values (1, 'Fender Musical Instruments Corporation', 3, 25000000, '1946-01-01');
58 | insert into manufacturer (id, name, location_id, averageYearlySales, foundedDate) values (2, 'Gibson Guitar Corporation', 42, 32000000, '1902-01-01');
59 |
60 | insert into modeltype (id, name) values (1, 'Dreadnought Acoustic');
61 | insert into modeltype (id, name) values (2, 'Nylon String Acoustic');
62 | insert into modeltype (id, name) values (3, 'Acoustic Electric');
63 | insert into modeltype (id, name) values (4, 'Electric');
64 | insert into modeltype (id, name) values (5, 'Hollow Body Electric');
65 | insert into modeltype (id, name) values (6, 'Semi-Hollow Body Electric');
66 | insert into modeltype (id, name) values (7, 'Bass');
67 |
68 | insert into model (id, name, manufacturer_id, modeltype_id, price, woodtype, yearfirstmade, frets) values (1, 'American Stratocaster', 1, 4, 1000, 'Maple, Alder, Ash, Popular', '1954-01-01', 21);
69 | insert into model (id, name, manufacturer_id, modeltype_id, price, woodtype, yearfirstmade, frets) values (2, 'American Telecaster', 1, 4, 800, 'Maple, Alder, Ash, Pine', '1950-01-01', 22);
70 | insert into model (id, name, manufacturer_id, modeltype_id, price, woodtype, yearfirstmade, frets) values (3, 'King', 1, 1, 600, 'Variety of high quality woods', '1963-01-01', 19);
71 | insert into model (id, name, manufacturer_id, modeltype_id, price, woodtype, yearfirstmade, frets) values (4, 'Precision Bass', 1, 7, 900, 'Alder and Ash', '1951-01-01', 21);
72 |
73 | insert into model (id, name, manufacturer_id, modeltype_id, price, woodtype, yearfirstmade, frets) values (5, 'Les Paul', 2, 4, 1600, 'Mahogany and Maple', '1952-01-01', 22);
74 | insert into model (id, name, manufacturer_id, modeltype_id, price, woodtype, yearfirstmade, frets) values (6, 'SG', 2, 4, 1200, 'Mahogany, Birch and Maple', '1961-01-01', 22);
75 | insert into model (id, name, manufacturer_id, modeltype_id, price, woodtype, yearfirstmade, frets) values (7, 'ES-335', 2, 6, 2200, 'Maple and Rosewood', '1958-01-01', 22);
76 | insert into model (id, name, manufacturer_id, modeltype_id, price, woodtype, yearfirstmade, frets) values (8, 'Hummingbird', 2, 1, 900, 'Spruce and Mahogany', '1960-01-01', 20);
77 | insert into model (id, name, manufacturer_id, modeltype_id, price, woodtype, yearfirstmade, frets) values (9, 'Thunderbird', 2, 7, 1500, 'Mahogany', '1963-01-01', 22);
78 |
--------------------------------------------------------------------------------
/src/main/resources/h2/db.h2.db:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dlbunker/ps-guitar-db/064693b3197203f803ddfe7e485fc8fa2b22a508/src/main/resources/h2/db.h2.db
--------------------------------------------------------------------------------
/src/test/java/com/guitar/db/LocationPersistenceTests.java:
--------------------------------------------------------------------------------
1 | package com.guitar.db;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import java.util.List;
6 |
7 | import javax.persistence.EntityManager;
8 | import javax.persistence.PersistenceContext;
9 |
10 | import org.junit.Test;
11 | import org.junit.runner.RunWith;
12 | import org.springframework.beans.factory.annotation.Autowired;
13 | import org.springframework.test.context.ContextConfiguration;
14 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
15 | import org.springframework.transaction.annotation.Transactional;
16 |
17 | import com.guitar.db.model.Location;
18 | import com.guitar.db.repository.LocationRepository;
19 |
20 | @ContextConfiguration(locations={"classpath:com/guitar/db/applicationTests-context.xml"})
21 | @RunWith(SpringJUnit4ClassRunner.class)
22 | public class LocationPersistenceTests {
23 | @Autowired
24 | private LocationRepository locationRepository;
25 |
26 | @PersistenceContext
27 | private EntityManager entityManager;
28 |
29 | @Test
30 | @Transactional
31 | public void testSaveAndGetAndDelete() throws Exception {
32 | Location location = new Location();
33 | location.setCountry("Canada");
34 | location.setState("British Columbia");
35 | location = locationRepository.create(location);
36 |
37 | // clear the persistence context so we don't return the previously cached location object
38 | // this is a test only thing and normally doesn't need to be done in prod code
39 | entityManager.clear();
40 |
41 | Location otherLocation = locationRepository.find(location.getId());
42 | assertEquals("Canada", otherLocation.getCountry());
43 | assertEquals("British Columbia", otherLocation.getState());
44 |
45 | //delete BC location now
46 | locationRepository.delete(otherLocation);
47 | }
48 |
49 | @Test
50 | public void testFindWithLike() throws Exception {
51 | List locs = locationRepository.getLocationByStateName("New");
52 | assertEquals(4, locs.size());
53 | }
54 |
55 | @Test
56 | @Transactional //note this is needed because we will get a lazy load exception unless we are in a tx
57 | public void testFindWithChildren() throws Exception {
58 | Location arizona = locationRepository.find(3L);
59 | assertEquals("United States", arizona.getCountry());
60 | assertEquals("Arizona", arizona.getState());
61 |
62 | assertEquals(1, arizona.getManufacturers().size());
63 |
64 | assertEquals("Fender Musical Instruments Corporation", arizona.getManufacturers().get(0).getName());
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/src/test/java/com/guitar/db/ManufacturerPersistenceTests.java:
--------------------------------------------------------------------------------
1 | package com.guitar.db;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import java.util.Date;
6 | import java.util.List;
7 |
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.test.context.ContextConfiguration;
12 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
13 |
14 | import com.guitar.db.model.Manufacturer;
15 | import com.guitar.db.repository.ManufacturerRepository;
16 |
17 | @ContextConfiguration(locations={"classpath:com/guitar/db/applicationTests-context.xml"})
18 | @RunWith(SpringJUnit4ClassRunner.class)
19 | public class ManufacturerPersistenceTests {
20 | @Autowired
21 | private ManufacturerRepository manufacturerRepository;
22 |
23 | @Test
24 | public void testGetManufacturersFoundedBeforeDate() throws Exception {
25 | List mans = manufacturerRepository.getManufacturersFoundedBeforeDate(new Date());
26 | assertEquals(2, mans.size());
27 | }
28 |
29 | @Test
30 | public void testGetManufactureByName() throws Exception {
31 | Manufacturer m = manufacturerRepository.getManufacturerByName("Fender");
32 | assertEquals("Fender Musical Instruments Corporation", m.getName());
33 | }
34 |
35 | @Test
36 | public void testGetManufacturersThatSellModelsOfType() throws Exception {
37 | List mans = manufacturerRepository.getManufacturersThatSellModelsOfType("Semi-Hollow Body Electric");
38 | assertEquals(1, mans.size());
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/test/java/com/guitar/db/ModelPersistenceTests.java:
--------------------------------------------------------------------------------
1 | package com.guitar.db;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import java.math.BigDecimal;
6 | import java.util.Date;
7 | import java.util.List;
8 |
9 | import javax.persistence.EntityManager;
10 | import javax.persistence.PersistenceContext;
11 |
12 | import org.junit.Test;
13 | import org.junit.runner.RunWith;
14 | import org.springframework.beans.factory.annotation.Autowired;
15 | import org.springframework.test.context.ContextConfiguration;
16 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
17 | import org.springframework.transaction.annotation.Transactional;
18 |
19 | import com.guitar.db.model.Model;
20 | import com.guitar.db.repository.ModelRepository;
21 |
22 | @ContextConfiguration(locations={"classpath:com/guitar/db/applicationTests-context.xml"})
23 | @RunWith(SpringJUnit4ClassRunner.class)
24 | public class ModelPersistenceTests {
25 | @Autowired
26 | private ModelRepository modelRepository;
27 |
28 | @PersistenceContext
29 | private EntityManager entityManager;
30 |
31 | @Test
32 | @Transactional
33 | public void testSaveAndGetAndDelete() throws Exception {
34 | Model m = new Model();
35 | m.setFrets(10);
36 | m.setName("Test Model");
37 | m.setPrice(BigDecimal.valueOf(55L));
38 | m.setWoodType("Maple");
39 | m.setYearFirstMade(new Date());
40 | m = modelRepository.create(m);
41 |
42 | // clear the persistence context so we don't return the previously cached location object
43 | // this is a test only thing and normally doesn't need to be done in prod code
44 | entityManager.clear();
45 |
46 | Model otherModel = modelRepository.find(m.getId());
47 | assertEquals("Test Model", otherModel.getName());
48 | assertEquals(10, otherModel.getFrets());
49 |
50 | //delete BC location now
51 | modelRepository.delete(otherModel);
52 | }
53 |
54 | @Test
55 | public void testGetModelsInPriceRange() throws Exception {
56 | List mods = modelRepository.getModelsInPriceRange(BigDecimal.valueOf(1000L), BigDecimal.valueOf(2000L));
57 | assertEquals(4, mods.size());
58 | }
59 |
60 | @Test
61 | public void testGetModelsByPriceRangeAndWoodType() throws Exception {
62 | List mods = modelRepository.getModelsByPriceRangeAndWoodType(BigDecimal.valueOf(1000L), BigDecimal.valueOf(2000L), "Maple");
63 | assertEquals(3, mods.size());
64 | }
65 |
66 | @Test
67 | public void testGetModelsByType() throws Exception {
68 | List mods = modelRepository.getModelsByType("Electric");
69 | assertEquals(4, mods.size());
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/src/test/java/com/guitar/db/ModelTypePersistenceTests.java:
--------------------------------------------------------------------------------
1 | package com.guitar.db;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import javax.persistence.EntityManager;
6 | import javax.persistence.PersistenceContext;
7 |
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.test.context.ContextConfiguration;
12 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
13 | import org.springframework.transaction.annotation.Transactional;
14 |
15 | import com.guitar.db.model.ModelType;
16 | import com.guitar.db.repository.ModelTypeRepository;
17 |
18 | @ContextConfiguration(locations={"classpath:com/guitar/db/applicationTests-context.xml"})
19 | @RunWith(SpringJUnit4ClassRunner.class)
20 | public class ModelTypePersistenceTests {
21 | @Autowired
22 | private ModelTypeRepository modelTypeRepository;
23 |
24 | @PersistenceContext
25 | private EntityManager entityManager;
26 |
27 | @Test
28 | @Transactional
29 | public void testSaveAndGetAndDelete() throws Exception {
30 | ModelType mt = new ModelType();
31 | mt.setName("Test Model Type");
32 | mt = modelTypeRepository.create(mt);
33 |
34 | // clear the persistence context so we don't return the previously cached location object
35 | // this is a test only thing and normally doesn't need to be done in prod code
36 | entityManager.clear();
37 |
38 | ModelType otherModelType = modelTypeRepository.find(mt.getId());
39 | assertEquals("Test Model Type", otherModelType.getName());
40 |
41 | modelTypeRepository.delete(otherModelType);
42 | }
43 |
44 | @Test
45 | public void testFind() throws Exception {
46 | ModelType mt = modelTypeRepository.find(1L);
47 | assertEquals("Dreadnought Acoustic", mt.getName());
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/test/resources/com/guitar/db/applicationTests-context.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/src/test/resources/log4j.properties:
--------------------------------------------------------------------------------
1 | log4j.rootCategory=INFO, stdout
2 |
3 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender
4 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
5 | log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n
6 |
7 | log4j.category.org.apache.activemq=ERROR
8 | log4j.category.org.springframework.batch=DEBUG
9 | log4j.category.org.springframework.transaction=INFO
10 |
11 | log4j.category.org.hibernate.SQL=DEBUG
12 | # for debugging datasource initialization
13 | # log4j.category.test.jdbc=DEBUG
14 |
--------------------------------------------------------------------------------