包阅导读总结
1.
关键词:Java Enums、JPA、PostgreSQL、Hypersistence Utils、Integration
2.
总结:本文介绍了如何将 Java 枚举与 JPA 和 PostgreSQL 枚举进行集成,包括项目设置、定义枚举、创建 PostgreSQL 枚举类型、配置 JPA 实体和编写主应用程序进行测试,最后强调了这种集成的优势。
3.
主要内容:
– 项目设置
– 创建 Maven 项目,在 `pom.xml` 中添加必要依赖:Hibernate Core、PostgreSQL 驱动、Hypersistence Utils 库。
– 定义 Java 枚举
– 定义 `Status` 枚举表示用户状态。
– 创建 PostgreSQL 枚举类型
– 执行 SQL 命令创建 `status` 枚举类型。
– 使用该枚举类型创建 `users` 表。
– 配置 JPA 实体
– 使用 `@TypeDef`、`@Enumerated` 和 `@Type` 注解配置 `Users` 实体类中的 `status` 字段。
– 编写主应用程序
– 创建 `EntityManagerFactory` 和 `EntityManager`。
– 开启事务,创建并持久化用户,提交事务,关闭 `EntityManager`。
– 重新创建 `EntityManager` 检索用户,输出用户详情,关闭 `EntityManager` 和 `EntityManagerFactory`。
– 结论
– 总结集成方法和优势。
思维导图:
文章地址:https://www.javacodegeeks.com/integrating-java-enums-with-jpa-and-postgresql-enums.html
文章来源:javacodegeeks.com
作者:Omozegie Aziegbe
发布时间:2024/7/31 11:17
语言:英文
总字数:823字
预计阅读时间:4分钟
评分:87分
标签:Java,JPA,PostgreSQL,Hibernate,Hypersistence 工具库
以下为原文内容
本内容来源于用户推荐转载,旨在分享知识与观点,如有侵权请联系删除 联系邮箱 media@ilingban.com
Enums are a powerful feature in Java, allowing us to define a fixed set of constants. When using JPA (Java Persistence API) with PostgreSQL, we might want to store these enums in a PostgreSQL enum type. This article demonstrates how to integrate Java enums with JPA and PostgreSQL enums.
1. Setting Up the Project
First, create a new Maven project and include the necessary dependencies in the pom.xml
file. These dependencies include Hibernate Core for JPA implementation, PostgreSQL driver for database connection, and Hypersistence Utils library to simplify working with PostgreSQL enums.
<dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.6.15.Final</version> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.4.1</version> </dependency> <dependency> <groupId>io.hypersistence</groupId> <artifactId>hypersistence-utils-hibernate-55</artifactId> <version>3.8.2</version> </dependency> </dependencies>
In this setup, the Hibernate Core dependency provides the JPA implementation, the PostgreSQL dependency is the JDBC driver for PostgreSQL, and Hypersistence Utils extends Hibernate with additional types and utilities that simplify handling PostgreSQL-specific features, like enums.
2. Define the Enum
Next, we define the Java enum, which will be used to represent the status of a user in our application.
public enum Status { ACTIVE, INACTIVE, SUSPENDED;}
This Status
enum contains three possible values: ACTIVE
, INACTIVE
, and SUSPENDED
. This will correspond directly to the PostgreSQL enum type we will create in the database.
3. Create the PostgreSQL Enum Type
Before we can use the Java enum with PostgreSQL, we need to create the corresponding enum type in our PostgreSQL database. Connect to your PostgreSQL database and execute the following SQL command:
CREATE TYPE status AS ENUM ('ACTIVE', 'INACTIVE', 'SUSPENDED');
This SQL command creates a new enum type named status
in PostgreSQL with the same values as our Java enum. This ensures consistency between our database schema and our application logic.
3.1 Create the Table Using the Enum Type
Next, create a table that uses the status
enum type.
CREATE TABLE users ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL, status status NOT NULL);
4. Configure the JPA Entity with Hypersistence Utils
Now, we configure our JPA entity to use the Status
enum. We will leverage the Hypersistence Utils library to map the PostgreSQL enum type to our Java enum.
@Entity@TypeDef( name = "pgsql_enum", typeClass = PostgreSQLEnumType.class)public class Users implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @Enumerated(EnumType.STRING) @Column(columnDefinition = "status") @Type(type = "pgsql_enum") private Status status; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } }
In this configuration, the @TypeDef
annotation registers the PostgreSQLEnumType
under the name pgsql_enum
. The @Enumerated(EnumType.STRING)
annotation specifies that the enum should be stored as a string in the database. The @Type(type = "pgsql_enum")
annotation tells Hibernate to use the PostgreSQLEnumType
for the status
field, ensuring the correct handling of the PostgreSQL enum type.
5. Write the Main Application
Finally, write the main application to test the integration. This application will create a new user, persist it to the database, and then retrieve it to verify the integration.
public class PostgresqlEnumTypeExample { public static void main(String[] args) { // Create an EntityManagerFactory EntityManagerFactory emf = Persistence.createEntityManagerFactory("postgresqlEnumTypeExamplePU"); // Create an EntityManager EntityManager em = emf.createEntityManager(); // Start a transaction em.getTransaction().begin(); // Create a new User Users user = new Users(); user.setName("Benjamin Fish"); user.setStatus(Status.ACTIVE); // Persist the User em.persist(user); // Commit the transaction em.getTransaction().commit(); // Close the EntityManager em.close(); // Open a new EntityManager to retrieve the User em = emf.createEntityManager(); Users retrievedUser = em.find(Users.class, user.getId()); System.out.println("Retrieved User: " + retrievedUser.getName() + ", Status: " + retrievedUser.getStatus()); // Close the EntityManager em.close(); // Close the EntityManagerFactory emf.close(); }}
When you run the main application, it should output the following:
Hibernate: insert into Users (name, status) values (?, ?)Hibernate: select users0_.id as id1_0_0_, users0_.name as name2_0_0_, users0_.status as status3_0_0_ from Users users0_ where users0_.id=?Retrieved User: Benjamin Fish, Status: ACTIVE
The application prints the retrieved user’s details to the console, confirming that the user has been successfully persisted and retrieved.
6. Conclusion
In this article, we explored how to integrate Java enums with JPA and PostgreSQL enums using the Hypersistence Utils library. We began by setting up a Maven project and including the necessary dependencies. We then defined a Java enum, created the corresponding PostgreSQL enum type and configured our JPA entity with the @JdbcType
and @Type
annotations from Hypersistence Utils. Finally, we demonstrated how to persist and retrieve data using a main application.
This setup allows us to leverage PostgreSQL’s enum types in a type-safe manner within our Java application, ensuring consistency and type safety across our application and database layers.
7. Download the Source Code
This article explores how to work with Java enums, JPA, and PostgreSQL.