JavaFX + Hibernate(JPA) 持久化 + Derby DB
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24810254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaFX + Hibernate(JPA) persistence + Derby DB
提问by Xavier ?au?ay
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.
我正在开发一个 Java 桌面应用程序,并且对使用 JavaFX 非常感兴趣。我计划使用 MVC 架构,因为我在 Java EE 和 MVC 模型方面有一些经验。
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.
我想将数据存储在嵌入式 derby 数据库中并使用 Hibernate 作为持久层,但我找不到关于使用 Hibernate 和 JavaFX 实现 MVC 的优秀教程。
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.
我已经创建了持久性文件,但我不确定如何使其与 JavaFX 一起使用。在 Java EE 中,我注入了 EJB 服务或 DAO,但由于我的应用程序未连接服务器,我想我不能这样做。
Can someone explain me how to achieve that? It is possible to use them together?
有人可以解释我如何实现这一目标吗?可以一起使用吗?
采纳答案by Patrick
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.
在我最近的一个 JavaFX 项目中,我在我的服务层下创建了一个 DataBroker 类,该类可以对数据库执行所有 CRUD 操作。
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.
如果你只需要一个DataBroker Instance,你也许可以将它实现为Singleton,如果你需要一个Pool of Instances,创建一个Pool。这是应用服务器的优势,他为您完成这一切,您只需注释您的类或成员。
I hope this will help you.
我希望这能帮到您。
EDIT / UPDATEHere is a working example with EclipseLink 2.1, but it is only the Persistence Provider, so it works also with Hibernate.
编辑/更新这是一个使用 EclipseLink 2.1 的工作示例,但它只是持久性提供程序,因此它也适用于 Hibernate。
I created a DataBroker like in the above example which implements my IDataBroker Interface and overrides the methods.
我在上面的例子中创建了一个 DataBroker,它实现了我的 IDataBroker 接口并覆盖了这些方法。
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...
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.
}
}
IPersonService Interface
IPerson 服务接口
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 FXMLControllerclass
该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();
}
}
And last but not least the MainApp to start the Application.
最后但并非最不重要的是 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);
}
}
This is a standard Maven JavaFX Project created with Netbeans 8. If necessary I can upload the Sources to GitHub or something..
这是使用 Netbeans 8 创建的标准 Maven JavaFX 项目。如有必要,我可以将源文件上传到 GitHub 或其他内容。
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
数据库表将在第一次提交时创建,因为我在 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>
So I hope this will help you to create your project.
所以我希望这会帮助你创建你的项目。
Patrick
帕特里克