Inserting objects

Figure 914. persistence.xml configuration Slide presentation Create comment in forum
<persistence...>
  <persistence-unit name = "strategy_drop-and-create">
    <properties>
      <property name = "javax.persistence.jdbc.driver"
                value="com.mysql.cj.jdbc.Driver"/>
      <property name = "javax.persistence.jdbc.url"
               value = "jdbc:mysql://localhost:3306/hdm"/>
      <property name = "javax.persistence.jdbc.user" value="hdmuser"/>
      <property name = "javax.persistence.jdbc.password" value="XYZ"/>

      <property name = "javax.persistence.schema-generation.database.action"
               value = "drop-and-create"/>
    </properties>
  </persistence-unit>
</persistence>

Figure 915. CreateStudyCourse using a transaction Slide presentation Create comment in forum
final EntityManagerFactory factory = 
 Persistence.createEntityManagerFactory(
   "strategy_drop-and-create") ;

final EntityManager entityManager = 
  factory.createEntityManager();

final EntityTransaction tx = 
      entityManager.getTransaction();
tx.begin(); 
  final StudyCourse csm = new StudyCourse(
   "CSM","Computer Science and Media"); 

  entityManager.persist(csm); 
tx.commit(); 
-- from logging









insert into 
  StudyCourse(
    fullName, shortName)
  values(?, ?)

Creating factory.

strategy_drop-and-create refers to the first persistence unit definition in resources/persistence.xml:

<persistence-unit name = "strategy_drop-and-create">
  <properties>
           ... <!-- JDBC related stuff omitted-->
    <property name = "javax.persistence.schema-generation.database.action"
             value = "drop-and-create"/>
</properties>

This setting causes JPA to drop and subsequently re-create all database tables being related to an @Entity annotated class.

Creating an EntityManager instance.

Creating an EntityTransaction instance.

Starting transaction.

Creating transient StudyCourse instance.

Binding transient StudyCourse instance to persistence context: The EntityManager takes control of the instance's life cycle.

Committing transaction thereby persisting the StudyCourse instance.

Figure 916. Database state Slide presentation Create comment in forum
MariaDB [hdm]> select * from StudyCourse;
+-----------+---------------------------+
| shortName | fullName                  |
+-----------+---------------------------+
| CSM       | Computer Science and Media|
+-----------+---------------------------+
1 row in set (0.00 sec)