Home > AI > Backend > SpringBoot > mysql-connector-java >

@NaturalId

The field is unique, otherwise duplication error would be triggered.

Example, save one entity, save Many-To-Many relationship, save One-To-One relationship, save One-To-Many relationship.

Post.java

@Data
@Entity(name = "Post")
@Table(name = "good_posts")
public class Post extends BaseEntity {


    @NaturalId
    private String title;

    @OneToMany(
            mappedBy = "post",
            cascade = CascadeType.PERSIST,
            orphanRemoval = true
    )
    private List<Comment> comments = new ArrayList();


    @OneToOne(
            mappedBy = "post",
            cascade = CascadeType.PERSIST,
            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;
    }
}

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
}

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
}

BaseEntity.java

@MappedSuperclass
public class BaseEntity {

    @Id
    @GeneratedValue
    private Long id;

    @Version
    private Integer version;

    //Getters and setters omitted for brevity
}

Demo11Application.java

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class Demo11Application implements CommandLineRunner {

	public static void main(String[] args) {

        EntityManagerFactory factory =
                Persistence.createEntityManagerFactory("PERSISTENCE1");
        EntityManager em = factory.createEntityManager();
        Session session = em.unwrap(Session.class);

        em.getTransaction().begin();



        // do whatever you want

        // find the entity with the unique natural id
        Tag t1 = session.bySimpleNaturalId(Tag.class).getReference("JDBC");
        if (t1 == null) {
            t1 = new Tag();
            t1.setName("JDBC");
            em.persist(t1);
        }

        Tag t2 = session.bySimpleNaturalId(Tag.class).getReference("Hibernate");
        if (t2 == null) {
            t2 = new Tag();
            t2.setName("Hibernate");
            em.persist(t2);
        }





        Post p = session.bySimpleNaturalId(Post.class).getReference("High-Performance Java Persistence");
        if (p == null) {
            p = new Post();
            p.setTitle("High-Performance Java Persistence");

            PostDetails postDetails = new PostDetails();
            postDetails.setCreatedBy("Vlad Mihalcea");
            postDetails.setCreatedOn(new Date());
            p.addDetails(postDetails);




            p.getTags().add(
                    session
                            .bySimpleNaturalId(Tag.class)
                            .getReference("JDBC")
            );
            p.getTags().add(
                    session
                            .bySimpleNaturalId(Tag.class)
                            .getReference("Hibernate")
            );


            em.persist(p);
        }






        Post pp = em.createQuery(
                        "select p " +
                                "from Post p " +
                                "where p.title = :title", Post.class)
                .setParameter("title", "High-Performance Java Persistence")
                .getSingleResult();

        Comment comment = new Comment();
        comment.setReview("THE book on Hibernate");
        pp.addComment(comment);




        em.getTransaction().commit();
        em.close();


//        SpringApplication.run(Demo11Application.class, args);
	}
}

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>

Leave a Reply