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

EntityManagerFactory

We can use EntityManagerFactory and EntityManager to replace JPARepository for the DAO

Example:

Firstly, let’s create these entities

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;
    }
}

PostDetais.java

import lombok.Data;

import javax.persistence.*;
import java.util.Date;

/**
 * @description
 */
@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

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 * @description
 */
@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

import lombok.Data;
import org.hibernate.annotations.NaturalId;

import javax.persistence.Entity;
import javax.persistence.Table;

/**
 * @description
 */
@Data
@Entity(name = "Tag")
@Table(name = "good_tags")
public class Tag extends BaseEntity {

    @NaturalId
    private String name;

    //Getters and setters omitted for brevity
}

Then, let’s create one additional file

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 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();



        // do whatever you want
        Tag t1 = new Tag();
        t1.setName("JDBC");
        em.persist(t1);

        Tag t2 = new Tag();
        t2.setName("Hibernate");
        em.persist(t2);



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

	}

 
}

You should see two records in the mysql database.

Hibernate would generate the two SQL

INSERT INTO tag (version, name)
VALUES (0, 'JDBC')
 
INSERT INTO tag (version, name)
VALUES (0, 'Hibernate')

Leave a Reply