Skip to content

Commit 4acbbd7

Browse files
Develop System 01Develop System 01
Develop System 01
authored and
Develop System 01
committedDec 17, 2022
added relation between Author and Book
1 parent e29c44a commit 4acbbd7

File tree

8 files changed

+356
-22
lines changed

8 files changed

+356
-22
lines changed
 

‎pom.xml

+8-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
1-
<project
2-
xmlns="http://maven.apache.org/POM/4.0.0"
3-
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4-
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
1+
<project xmlns="http://maven.apache.org/POM/4.0.0"
2+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
53
<modelVersion>4.0.0</modelVersion>
64
<groupId>com.jpa.example</groupId>
75
<artifactId>jpaEntityManager</artifactId>
@@ -50,6 +48,12 @@
5048
<version>3.0.2</version>
5149
</dependency>
5250

51+
<dependency>
52+
<groupId>com.fasterxml.jackson.core</groupId>
53+
<artifactId>jackson-databind</artifactId>
54+
<version>2.13.3</version>
55+
</dependency>
56+
5357
<!-- Test -->
5458
<dependency>
5559
<groupId>junit</groupId>

‎src/main/java/com/jpa/example/Application.java

+140-13
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package com.jpa.example;
22

3+
// import jakarta.json.Json;
4+
// import jakarta.json.JsonValue;
35
import jakarta.persistence.*;
46
import jakarta.persistence.criteria.CriteriaBuilder;
57
import jakarta.persistence.criteria.CriteriaQuery;
@@ -10,11 +12,17 @@
1012
// import java.nio.charset.StandardCharsets;
1113
import java.io.InputStream;
1214
import java.time.LocalDate;
15+
import java.util.ArrayList;
1316
import java.util.Arrays;
1417
//import java.util.List;
18+
import java.util.HashMap;
19+
import java.util.List;
1520

21+
//import com.fasterxml.jackson.databind.util.JSONPObject;
1622
import com.jpa.example.models.Author;
1723
import com.jpa.example.models.Book;
24+
import com.jpa.example.models.EntityA;
25+
import com.jpa.example.models.EntityB;
1826
import com.jpa.example.models.MyObject;
1927

2028
public class Application {
@@ -51,26 +59,73 @@ public static void main(String[] args) {
5159

5260
}
5361

62+
{
63+
EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistence");
64+
try {
65+
persistEntity(emf);
66+
nativeQueries(emf);
67+
loadEntityA(emf);
68+
loadEntityB(emf);
69+
}
70+
71+
finally {
72+
emf.close();
73+
}
74+
System.out.println("Press Enter to continue");
75+
76+
try {
77+
78+
System.in.read();
79+
80+
}
81+
catch( Exception ex ){
82+
83+
//
84+
85+
}
86+
87+
}
88+
5489
EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistence");
5590
EntityManager entityManager = emf.createEntityManager();
5691
entityManager.getTransaction().begin();
5792

58-
Author author = new Author();
59-
author.Name = "Tomas Moreno";
60-
author.BirthYear = 1979;
61-
entityManager.persist(author);
62-
63-
//var id = author.Id;
93+
Author author01 = new Author();
94+
author01.Name = "Tomas Moreno";
95+
author01.BirthYear = 1979;
96+
author01.bookList = new ArrayList<>();
97+
author01.ExtraData = new HashMap<>();
98+
author01.ExtraData.put( "Field1" , "Value1" );
99+
author01.ExtraData.put( "Field2" , "Value2" );
100+
//entityManager.persist(author01);
101+
102+
Book book01 = new Book();
103+
book01.Title = "GraalVM/Native-Image the future of Java";
104+
book01.PubDate = LocalDate.now();
105+
book01.Author = author01;
106+
//book01.setAuthor( author01 );
107+
entityManager.persist(book01);
108+
109+
Book book02 = new Book();
110+
book02.Title = "Java 2017";
111+
book02.PubDate = LocalDate.now();
112+
book02.Author = author01;
113+
//book02.setAuthor( author01 );
114+
entityManager.persist(book02);
115+
116+
author01.bookList = Arrays.asList( book01, book02 );
117+
//author01.setBookList( Arrays.asList( book01, book02 ) );
118+
entityManager.persist(author01);
64119

65-
findAuthorById( entityManager, author.Id );
120+
findAuthorById( entityManager, author01.Id );
121+
findBookById( entityManager, book01.Id );
66122

67-
Book book = new Book();
68-
book.Title = "GraalVM/Native-Image the future of Java";
69-
book.PubDate = LocalDate.now();
70-
book.Author = author;
71-
entityManager.persist(book);
123+
Author author02 = new Author();
124+
author02.Name = "Loly Gomez";
125+
author02.BirthYear = 1980;
126+
entityManager.persist(author02);
72127

73-
findBookById( entityManager, book.Id );
128+
//var id = author.Id;
74129

75130
MyObject myObject = new MyObject();
76131
myObject.Data = "one";
@@ -139,12 +194,14 @@ private static void findAuthorById(EntityManager entityManager, String id ) {
139194
System.out.println("----\nfinding author by id");
140195
var o = entityManager.find(Author.class, id ); //2L);
141196
System.out.println(o);
197+
System.out.println( "book list =>" + o.bookList.toString() );
142198
}
143199

144200
private static void findBookById(EntityManager entityManager, String id ) {
145201
System.out.println("----\nfinding book by id");
146202
var o = entityManager.find(Book.class, id ); //2L);
147203
System.out.println(o);
204+
System.out.println( "author =>" + o.Author.toString() );
148205
}
149206

150207
private static void findObjectById(EntityManager entityManager, String id ) {
@@ -193,4 +250,74 @@ private static void criteriaQuery(EntityManager entityManager) {
193250
System.out.println(typedQuery.getResultList());
194251

195252
}
253+
254+
public static void nativeQuery(EntityManager em, String s) {
255+
System.out.printf("-----------------------------%n'%s'%n", s);
256+
Query query = em.createNativeQuery(s);
257+
List<?> list = query.getResultList();
258+
for (Object o : list) {
259+
if(o instanceof Object[]) {
260+
System.out.println(Arrays.toString((Object[]) o));
261+
}else{
262+
System.out.println(o);
263+
}
264+
}
265+
}
266+
267+
private static void nativeQueries(EntityManagerFactory emf) {
268+
System.out.println("-- nativeQueries --");
269+
EntityManager em = emf.createEntityManager();
270+
Application.nativeQuery(em, "Select * from EntityA");
271+
Application.nativeQuery(em, "Select * from EntityB");
272+
}
273+
274+
private static void persistEntity(EntityManagerFactory emf) {
275+
System.out.println("-- persistEntity --");
276+
EntityManager em = emf.createEntityManager();
277+
278+
EntityB entityB1 = new EntityB();
279+
entityB1.setStrB("testStringB");
280+
281+
EntityB entityB2 = new EntityB();
282+
entityB2.setStrB("testStringB2");
283+
284+
EntityA entityA = new EntityA();
285+
entityA.setStrA("testStringA");
286+
entityA.setEntityBList(Arrays.asList(entityB1, entityB2));
287+
288+
entityB1.setRefEntityA(entityA);
289+
entityB2.setRefEntityA(entityA);
290+
291+
System.out.println("-- persisting entities --");
292+
System.out.printf(" %s%n entityA#entityBList: %s%n", entityA, entityA.getEntityBList());
293+
System.out.printf(" %s%n entityB1#refEntityA: %s%n", entityB1, entityB1.getRefEntityA());
294+
System.out.printf(" %s%n entityB2#refEntityA: %s%n", entityB2, entityB2.getRefEntityA());
295+
296+
em.getTransaction().begin();
297+
em.persist(entityA);
298+
em.persist(entityB1);
299+
em.persist(entityB2);
300+
em.getTransaction().commit();
301+
302+
em.close();
303+
}
304+
305+
@SuppressWarnings("unchecked")
306+
private static void loadEntityA(EntityManagerFactory emf) {
307+
System.out.println("-- loadEntityA --");
308+
EntityManager em = emf.createEntityManager();
309+
List<EntityA> entityAList = em.createQuery("Select t from EntityA t").getResultList();
310+
entityAList.forEach(e -> System.out.printf(" %s%n entityA#entityBList: %s%n", e, e.getEntityBList()));
311+
em.close();
312+
}
313+
314+
@SuppressWarnings("unchecked")
315+
private static void loadEntityB(EntityManagerFactory emf) {
316+
System.out.println("-- loadEntityB --");
317+
EntityManager em = emf.createEntityManager();
318+
List<EntityB> entityBList = em.createQuery("Select t from EntityB t").getResultList();
319+
entityBList.forEach(e -> System.out.printf(" %s%n entityB#refEntityA: %s%n", e, e.getRefEntityA()));
320+
em.close();
321+
}
322+
196323
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.jpa.example.converter;
2+
3+
import java.util.HashMap;
4+
//import java.util.Map;
5+
6+
//import com.fasterxml.jackson.annotation.JsonValue;
7+
import com.fasterxml.jackson.core.JsonProcessingException;
8+
import com.fasterxml.jackson.core.type.TypeReference;
9+
import com.fasterxml.jackson.databind.ObjectMapper;
10+
11+
//import jakarta.json.Json;
12+
import jakarta.persistence.AttributeConverter;
13+
import jakarta.persistence.Converter;
14+
15+
//
16+
@Converter //(autoApply = true)
17+
public class JpaConverterJson implements AttributeConverter<HashMap<String, Object>, String> {
18+
19+
private final static ObjectMapper objectMapper = new ObjectMapper();
20+
21+
@Override
22+
public String convertToDatabaseColumn(HashMap<String, Object> meta) {
23+
try {
24+
if ( meta==null ) return null; // meta = new HashMap<String,Object>();
25+
return objectMapper.writeValueAsString(meta);
26+
}
27+
catch (JsonProcessingException ex) {
28+
return null;
29+
// or throw an error
30+
}
31+
}
32+
33+
@Override
34+
public HashMap<String, Object> convertToEntityAttribute(String dbData) {
35+
try {
36+
return objectMapper.readValue(dbData, new TypeReference<HashMap<String, Object>>() {});
37+
}
38+
catch (Exception ex) {
39+
// logger.error("Unexpected IOEx decoding json from database: " + dbData);
40+
return null;
41+
}
42+
}
43+
44+
}

‎src/main/java/com/jpa/example/models/Author.java

+60-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,30 @@
11
package com.jpa.example.models;
22

3+
import java.util.HashMap;
4+
import java.util.List;
5+
// import java.util.HashSet;
6+
// import java.util.Map;
7+
// import java.util.Set;
8+
9+
import com.jpa.example.converter.JpaConverterJson;
10+
11+
//import java.util.HashMap;
12+
//import java.util.Map;
13+
//import java.util.Map;
14+
15+
//import com.fasterxml.jackson.annotation.JsonValue;
16+
17+
//import java.util.Map;
18+
19+
//import com.fasterxml.jackson.databind.JsonNode;
20+
// import com.jpa.example.converter.JpaConverterJson;
21+
22+
// import jakarta.json.Json;
23+
// import jakarta.json.JsonObject;
24+
//import jakarta.json.JsonValue;
25+
//import jakarta.json.JsonValue;
26+
//import jakarta.json.JsonValue;
27+
//import jakarta.json.JsonObject;
328
import jakarta.persistence.*;
429
import jakarta.validation.constraints.Size;
530

@@ -9,7 +34,7 @@ public class Author {
934

1035
@Id
1136
@GeneratedValue(strategy = GenerationType.UUID)
12-
@Column(name="Id")
37+
@Column(name="Id",nullable = false)
1338
public String Id;
1439

1540
@Column(name="Name", nullable = false, unique = true)
@@ -19,12 +44,45 @@ public class Author {
1944
@Column(name="BirthYear", nullable = false)
2045
public Integer BirthYear;
2146

47+
@Column(name="ExtraData", nullable = true)
48+
@Convert(converter = JpaConverterJson.class) //, attributeName = "ExtraData")
49+
//@ElementCollection
50+
public HashMap<String,Object> ExtraData = null; // = new HashMap<>();
51+
52+
// @OneToMany //(targetEntity = Book.class, mappedBy="Author")
53+
// @JoinTable( name="Book",
54+
// joinColumns=@JoinColumn(name="Id", referencedColumnName="AuthorId"),
55+
// inverseJoinColumns=@JoinColumn(name="AuthorId"))
56+
//@JoinColumn(name = "AuthorId")
57+
@OneToMany( mappedBy = "Author" ) //,cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
58+
//@JoinColumn(name = "AuthorId")
59+
//public Set<Book> books = new HashSet<>();
60+
public List<Book> bookList;
61+
62+
// public Map<String, Object> getExtraData() {
63+
// return ExtraData;
64+
// }
65+
66+
// public void setExtraData(Map<String, Object> extraData) {
67+
// ExtraData = extraData;
68+
// }
69+
70+
// public List<Book> getBookList() {
71+
// return bookList;
72+
// }
73+
74+
// public void setBookList(List<Book> bookList) {
75+
// this.bookList = bookList;
76+
// }
77+
2278
public Author() {}
2379

2480
@Override
2581
public String toString () {
2682

27-
return "Author{ Id='" + Id + "', Name='" + Name + "', BirdYear='" + BirthYear + "' }";
83+
//var bookList = this.getBookList();
84+
85+
return "Author{ Id='" + Id + "', Name='" + Name + "', BirdYear='" + BirthYear + "', ExtraData='" + ( ExtraData != null ? ExtraData.toString(): null ) + "' }";
2886

2987
}
3088

‎src/main/java/com/jpa/example/models/Book.java

+11-3
Original file line numberDiff line numberDiff line change
@@ -20,16 +20,24 @@ public class Book {
2020
@Column(name="PubDate", columnDefinition = "DATE")
2121
public LocalDate PubDate;
2222

23-
@ManyToOne(targetEntity = Author.class)
24-
@JoinColumn(name = "AuthorId")
23+
@ManyToOne //(targetEntity = Author.class)
24+
//@JoinColumn(name = "AuthorId")
2525
public Author Author;
2626

27+
// public Author getAuthor() {
28+
// return Author;
29+
// }
30+
31+
// public void setAuthor(Author author) {
32+
// Author = author;
33+
// }
34+
2735
public Book() {}
2836

2937
@Override
3038
public String toString () {
3139

32-
return "Author{ Id='" + Id + "', Title='" + Title + "', PubDate='" + PubDate + "', Author=" + Author.toString() + " }";
40+
return "Book{ Id='" + Id + "', Title='" + Title + "', PubDate='" + PubDate + "' }";
3341

3442
}
3543

0 commit comments

Comments
 (0)
Please sign in to comment.