Home > Articles > Data > MySQL

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Setting Up the Persistence Unit

The persistence unit is required to allow communication between the Java code and the underlying database. The file persistence.xml contains all that is required as illustrated in Listing 12:

Listing 12—The File persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=
"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="punit">
        <property name="javax.persistence.jdbc.password" value="YOUR PASSWORD GOES HERE"/>
        <property name="javax.persistence.jdbc.user" value="root"/>
        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/quickstart"/>
        <property name="javax.persistence.logging.level" value="INFO"/>

In Listing 12, the persistence unit has the name punit. This name is used in the client code—e.g., Listing 5. Also included in the persistence.xml file is the list of Java classes that form part of the persistence unit. The next section of the persistence unit relates to the database engine (MySQL) and the details required to connect to that engine. The last part of the persistence unit indicates the logging level used in the console output.

Running the Code

Once your database is set up as illustrated in Listing 7, you can then run the Listing 11 client code simply by right-clicking the ClientCreate.java class and selecting Run As > Java Application. This will run the code from Listing 11 and create the database entities.


There is a huge amount of interest in database technology, specifically relational databases. Data mining is big business as organizations seek to monetize the data they collect through their various channels of web, mobile, etc. Because of this, a solid knowledge of object relational mapping is increasingly mandatory.

Collections represent an association between entities, and you've seen how to implement a simple unidirectional one-to-many relationship between entities. You can expect to see far more complex relationships than this in your work—e.g., many-to-many associations. However, the concepts are not so very different than the above discussion.

In Part 2 of this mini-series, I'll have a look at the area of stored procedures in MySQL.

Also, please download the code mentioned in this article.

  • + Share This
  • 🔖 Save To Your Account