Spring JPA: insert parent<->child at the same time
authorGustavo Martin Morcuende <gu.martinm@gmail.com>
Sun, 10 Jul 2016 16:59:21 +0000 (18:59 +0200)
committerGustavo Martin Morcuende <gu.martinm@gmail.com>
Sun, 10 Jul 2016 17:01:22 +0000 (19:01 +0200)
SpringJava/JPA/src/main/java/de/spring/example/persistence/domain/Ad.java
SpringJava/JPA/src/main/java/de/spring/example/persistence/domain/AdDescription.java

index df2046f..d1ad0df 100644 (file)
@@ -13,7 +13,6 @@ import javax.persistence.GeneratedValue;
 import javax.persistence.GenerationType;
 import javax.persistence.Id;
 import javax.persistence.JoinColumn;
-import javax.persistence.JoinTable;
 //import javax.persistence.NamedNativeQueries;
 //import javax.persistence.NamedNativeQuery;
 //import javax.persistence.NamedQueries;
@@ -66,16 +65,8 @@ public class Ad implements Serializable {
        @Column(name="id", updatable=false, nullable=false)
        private Long id;
        
-//  1. Using just OneToMany:
-//     @OneToMany(mappedBy="ad", fetch=FetchType.LAZY,
-//                     cascade = CascadeType.ALL, targetEntity=AdDescription.class)
-//  2. The same using @OneToMany + @JoinTable:
-       @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, targetEntity=AdDescription.class)
-       @JoinTable(
-            name="ad_description",
-            joinColumns = @JoinColumn( name="id"),
-            inverseJoinColumns = @JoinColumn( name="ad_id")
-        )
+       @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL)
+       @JoinColumn(name = "ad_id", nullable = false)
        private Set<AdDescription> adDescriptions;
        
        @Max(60)
@@ -119,6 +110,10 @@ public class Ad implements Serializable {
                this.updatedAt = updatedAt;
        }
 
+       /**
+        * WARNING: JPA REQUIRES GETTERS!!!
+        */
+       
        public Long getId() {
                return id;
        }
index a0fde9b..85f300c 100644 (file)
@@ -25,8 +25,8 @@ public class AdDescription implements Serializable {
        @Column(name="id", updatable=false, nullable=false)
        private Long id;
        
-       @ManyToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL, optional=false)
-       @JoinColumn(name="ad_id", referencedColumnName="id")
+       @ManyToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL, optional=true)
+       @JoinColumn(name="ad_id", nullable=false, updatable = false, insertable = false, referencedColumnName="id")
        private Ad ad;
        
        @NotNull
@@ -70,6 +70,10 @@ public class AdDescription implements Serializable {
                this.adMobileText = adMobileText;
                this.adLink = adLink;
        }
+       
+       /**
+        * WARNING: JPA REQUIRES GETTERS!!!
+        */
 
        public Long getId() {
                return id;