gpt4 book ai didi

JavaFX + Hibernate(JPA) 持久化 + Derby DB

转载 作者:行者123 更新时间:2023-12-01 16:11:26 26 4
gpt4 key购买 nike

我正在开发一个 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实例,您也许可以将其实现为单例,如果您需要一个实例池,则创建一个池。这是应用程序服务器的优势,他为您完成这一切,您只需注释您的类或成员。

希望这对您有帮助。

编辑/更新这是一个使用 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 <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);
}

人员服务

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

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


}

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", "demo@example.com");
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 项目。如果需要,我可以将源代码上传到 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>

所以我希望这能帮助您创建您的项目。

帕特里克

关于JavaFX + Hibernate(JPA) 持久化 + Derby DB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24810254/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com