JavaFX + Hibernate(JPA) persistence + Derby DB

2020-05-24 17:48发布

问题:

I'm developing a Java desktop application and was really interested in use JavaFX. I'm planning to use an MVC architecture because I have had some experience with Java EE and the MVC model.

I want to store data in a embedded derby database and use Hibernate as persistence layer but I can't find a great tutorial about implementing MVC with hibernate and JavaFX.

I have created the persistence file but I am not sure how to make it work with JavaFX. In Java EE I inject EJB services or DAOs but since my app is not server connected I think I can't do that.

Can someone explain me how to achieve that? It is possible to use them together?

回答1:

In one of my last JavaFX Projects, I created under my Service Layer a DataBroker class, which could do all the CRUD Operations on the Database.

Example:

public class DataBroker {

    private EntityManager em;

    public DataBroker() {
        init();
    }

    private void init() {
        this.em = Persistence.createEntityManagerFactory("<NAME_OF_YOUR_PU>").createEntityManager();
    }

    public Person saveOrUpdate(Person entity) {
        em.getTransaction().begin();
        T savedEntity = em.merge(entity);
        em.getTransaction().commit();
        return savedEntity;
    }

    public List<Person> getAllPersons() {
        TypedQuery<Person> query = em.createNamedQuery(Person.GET_ALL, Person.class);
        return query.getResultList();
    }

}

If you only need one DataBroker Instance, you maybe can realize it as a Singleton, if you need a Pool of Instances, create a Pool. This is the advantage of a Application Server, he does this all for you and you only have to annotate your Classes or Members.

I hope this will help you.

EDIT / UPDATE Here is a working example with EclipseLink 2.1, but it is only the Persistence Provider, so it works also with Hibernate.

I created a DataBroker like in the above example which implements my IDataBroker Interface and overrides the methods.

IDataBroker

import de.professional_webworkx.crm.domain.Person;
import java.util.List;


public interface IDateBroker {

    public abstract void saveOrUpdate(Person person);
    public abstract List<Person> getAllPersons();
    public abstract Person getPersonById(int id);
    public abstract Person getPersonByEmail(String email);
}

DataBroker - not every method is implemented...

import de.professional_webworkx.crm.domain.Person;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;

/**
 *
 * @author Patrick Ott <Patrick.Ott@professional-webworkx.de>
 * @version 1.0
 */
public class DataBroker implements IDateBroker {

    private EntityManager em;

    public DataBroker() {
        em = Persistence.createEntityManagerFactory("CRMPU").createEntityManager();
    }



    @Override
    public void saveOrUpdate(Person person) {
        em.getTransaction().begin();
        em.merge(person);
        em.getTransaction().commit();
    }

    @Override
    public List<Person> getAllPersons() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Person getPersonById(int id) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Person getPersonByEmail(String email) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }


}

IPersonService Interface

import de.professional_webworkx.crm.domain.Person;
import java.util.List;


public interface IPersonService {

    void saveOrUpdate(Person person);
    List<Person> getAllPersons();
    Person getPersonById(int id);
    Person getPersonByEmail(String email);
}

PersonService

import de.professional_webworkx.crm.databroker.DataBroker;
import de.professional_webworkx.crm.databroker.IDateBroker;
import de.professional_webworkx.crm.domain.Person;
import java.util.List;


public class PersonService implements IPersonService {

    private IDateBroker broker;

    public PersonService() {
        broker = new DataBroker();
    }

    @Override
    public void saveOrUpdate(Person person) {
        broker.saveOrUpdate(person);
    }

    @Override
    public List<Person> getAllPersons() {
        return broker.getAllPersons();
    }

    @Override
    public Person getPersonById(int id) {
        return broker.getPersonById(id);
    }

    @Override
    public Person getPersonByEmail(String email) {
        return broker.getPersonByEmail(email);
    }
}

Our Domain class Person

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;


@Entity
@Table(name = "person")
public class Person implements Serializable {

    private long id;
    private String firstName;
    private String lastName;
    private String eMail;

    public Person() {
    }

    public Person(String firstName, String lastName, String eMail) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.eMail = eMail;
    }


    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long getId() {
        return id;
    }


    public void setId(long id) {
        this.id = id;
    }


    @Size(min = 2, max = 255, message = "Enter between 2 and 255 characters!")
    @Column(name = "firstname")
    @NotNull
    public String getFirstName() {
        return firstName;
    }


    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }


    @Column(name = "lastname")
    @NotNull
    public String getLastName() {
        return lastName;
    }


    public void setLastName(String lastName) {
        this.lastName = lastName;
    }


    @NotNull
    public String geteMail() {
        return eMail;
    }


    public void seteMail(String eMail) {
        this.eMail = eMail;
    }


}

The FXMLController class

import de.professional_webworkx.crm.business.IPersonService;
import de.professional_webworkx.crm.business.PersonService;
import de.professional_webworkx.crm.domain.Person;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;

public class FXMLController implements Initializable {

    private IPersonService service;

    @FXML
    private Label label;

    @FXML
    private void handleButtonAction(ActionEvent event) {
        Person p = new Person("Demo", "User", "demo@example.com");
        service.saveOrUpdate(p);
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // get an instance of PersonService
        service = new PersonService();

    }    
}

And last but not least the MainApp to start the Application.

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;


public class MainApp extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));

        Scene scene = new Scene(root);
        scene.getStylesheets().add("/styles/Styles.css");

        stage.setTitle("JavaFX and Maven");
        stage.setScene(scene);
        stage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }

}

This is a standard Maven JavaFX Project created with Netbeans 8. If necessary I can upload the Sources to GitHub or something..

The Database Table will be created with the first commit, because i set up in the persistence.xml file, that Schema Generation as you can see from the file

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" 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">
  <persistence-unit name="CRMPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>de.professional_webworkx.crm.domain.Person</class>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/exampleDb?zeroDateTimeBehavior=convertToNull"/>
      <property name="javax.persistence.jdbc.user" value="user"/>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="javax.persistence.jdbc.password" value="pass"/>
      <property name="javax.persistence.schema-generation.database.action" value="create"/>
    </properties>
  </persistence-unit>
</persistence>

So I hope this will help you to create your project.

Patrick