我正在开发Java桌面应用程序,并且对使用JavaFX非常感兴趣。我计划使用MVC架构,因为我对Java EE和MVC模型有一定的经验。

我想将数据存储在嵌入式derby数据库中,并使用Hibernate作为持久层,但是找不到关于使用hibernate和JavaFX实现MVC的出色教程。

我已经创建了持久性文件,但不确定如何使其与JavaFX一起使用。在Java EE中,我注入(inject)了EJB服务或DAO,但是由于我的应用程序未与服务器连接,所以我认为我不能这样做。

有人可以解释我如何实现这一目标吗?可以一起使用吗?

最佳答案

在我的最后一个JavaFX项目中,我在服务层下创建了一个DataBroker类,该类可以执行数据库上的所有CRUD操作。

例:

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

}

如果仅需要一个DataBroker实例,则可以将其实现为Singleton,如果需要实例池,请创建一个池。这是Application Server的优势,他可以为您完成所有这些工作,而您只需注释您的类或成员。

我希望这能帮到您。

编辑/更新
这是EclipseLink 2.1的一个有效示例,但它只是Persistence Provider,因此它也适用于Hibernate。

我像上面的示例中一样创建了一个DataBroker,它实现了IDataBroker接口(interface)并覆盖了方法。

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 -并非每种方法都已实现...
import de.professional_webworkx.crm.domain.Person;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;

/**
 *
 * @author Patrick Ott <[email protected]>
 * @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.
    }


}

IPerson服务接口(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);
    }
}

我们的域类人员
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;
    }


}

FXMLController
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", "[email protected]");
        service.saveOrUpdate(p);
    }

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

    }
}

最后但并非最不重要的MainApp启动应用程序。
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);
    }

}

这是使用Netbeans 8创建的标准Maven JavaFX项目。如有必要,我可以将Sources上传到GitHub或其他东西。

数据库表将在第一次提交时创建,因为我在persistence.xml文件中进行了设置,从文件中可以看到该模式生成
<?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>

因此,我希望这将有助于您创建项目。

帕特里克

10-07 22:15