This example shows how to save for ManyToMany and OneToOne relationship.
Firstly, let’s create entity classes,
BaseEntity.java
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
/**
* @description
*/
@MappedSuperclass
public class BaseEntity {
@Id
@GeneratedValue
private Long id;
@Version
private Integer version;
//Getters and setters omitted for brevity
}
Post.java
@Data
@Entity(name = "Post")
@Table(name = "good_posts")
public class Post extends BaseEntity {
private String title;
@OneToMany(
mappedBy = "post",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<Comment> comments = new ArrayList();
@OneToOne(
mappedBy = "post",
cascade = CascadeType.ALL,
orphanRemoval = true,
fetch = FetchType.LAZY
)
private PostDetails details;
@ManyToMany
@JoinTable(
name = "good_posts_tags",
joinColumns = @JoinColumn(name = "post_id"),
inverseJoinColumns = @JoinColumn(name = "tag_id")
)
private Set<Tag> tags = new HashSet();
public void addComment(Comment comment) {
comments.add(comment);
comment.setPost(this);
}
public void addDetails(PostDetails details) {
this.details = details;
details.setPost(this);
}
public void removeDetails() {
this.details.setPost(null);
this.details = null;
}
}
PostDetail.java
@Data
@Entity(name = "PostDetails")
@Table(name = "good_post_details")
public class PostDetails extends BaseEntity {
@Column(name = "created_on")
private Date createdOn;
@Column(name = "created_by")
private String createdBy;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
private Post post;
}
Comment.java
@Data
@Entity(name = "PostComment")
@Table(name = "good_comments")
public class Comment extends BaseEntity {
@ManyToOne(fetch = FetchType.LAZY)
private Post post;
private String review;
//Getters and setters omitted for brevity
}
Tag.java
@Data
@Entity(name = "Tag")
@Table(name = "good_tags")
public class Tag extends BaseEntity {
@NaturalId
private String name;
//Getters and setters omitted for brevity
}
Secondly, let’s load the entity manager
resources/META-INF/persistence.xml
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="PERSISTENCE1">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
Finally, let’s do the test
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class Demo11Application implements CommandLineRunner {
public static void main(String[] args) {
EntityManagerFactory factory =
Persistence.createEntityManagerFactory("PERSISTENCE1");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
// now you can do whatever you want
Post post = new Post();
post.setTitle("High-Performance Java Persistence");
PostDetails postDetails = new PostDetails();
postDetails.setCreatedBy("Vlad Mihalcea");
postDetails.setCreatedOn(new Date());
post.addDetails(postDetails);
Session session = em.unwrap(Session.class);
post.getTags().add(
session
.bySimpleNaturalId(Tag.class)
.getReference("jdbc")
);
post.getTags().add(
session
.bySimpleNaturalId(Tag.class)
.getReference("hibernate")
);
em.persist(post);
em.getTransaction().commit();
em.close();
}
}
Now, you can see the record. in your mysql database
Hibernate does the following SQL
NSERT INTO post (version, title)
VALUES (0, 'High-Performance Java Persistence')
INSERT INTO post_details (version, created_by, created_on, id)
VALUES (0, 'Vlad Mihalcea', '2017-11-08 12:29:23.498', 1)
INSERT INTO post_tag (post_id, tag_id)
values (1, 2)
INSERT INTO post_tag (post_id, tag_id)
values (1, 1)