定义一个JPA Entity 类

    xiaoxiao2022-06-30  98

    前言

    本文是介绍Java的JPA的Entity的类,个别地方记录一下笔记。 

    原文

    Defining a JPA Entity Class

    To be able to store Point objects in the database using JPA we need to define an entity class. A JPA entity class is a POJO (Plain Old Java Object) class, i.e. an ordinary Java class that is marked (annotated) as having the ability to represent objects in the database. Conceptually this is similar to serializable classes, which are marked as having the ability to be serialized.

    JPA Entity类是一个POJO,意思就是一个简单的老的Java对象,这个是区别于EJB里面对于Bean的那些额外的定义的。这样的类被一个注解(@Entity)所标注,就拥有能力去代表数据库的一个对象。

    The Point Entity Class

    The following Point class, which represents points in the plane, is marked as an entity class, and accordingly, provides the ability to store Point objects in the database and retrieve Point objects from the database:

    package com.objectdb.tutorial; import javax.persistence.Entity; @Entity public class Point { // Persistent Fields: private int x; private int y; // Constructor: Point (int x, int y) { this.x = x; this.y = y; } // Accessor Methods: public int getX() { return this.x; } public int getY() { return this.y; } // String Representation: @Override public String toString() { return String.format("(%d, %d)", this.x, this.y); } }

    As you can see above, an entity class is an ordinary Java classhe only unique JPA addition is the @Entity annotation, which marks the class as an entity class.

    An attempt to persist Point objects in the database without marking the Point class as an entity class will cause a PersistenceException. This is similar to the NotSerializableException that Java throws (unrelated to JPA), Java IO exceptions are checked).

    没有标记注解,会导致抛出一个PersistenceException的异常。

    Persistent Fields in Entity Classes

    Storing an entity object in the database does not store methods and code are x and y (representing the position of the point in the plane). It is the values of these fields that are stored in the database when an entity object is persisted.

    Chapter 2 provides additional information on how to define entity classes, including which persistent types can be used for persistent fields, how to define and use a primary key and what a version field is and how to use it.

    If you are already familiar with JPA you might have noticed that the Point entity class has no primary key (@Id) field defined. As an object database, ObjectDB supports implicit object IDs, so an explicitly defined primary key is not required. On the other hand, ObjectDB also supports explicit JPA primary keys,  including composite primary keys and automatic sequential value generation. This is a very powerful feature of ObjectDB that is absent from other object oriented databases.

    @Id这个注解有特殊的含义,这个是用来标示主键的,这里并没有太多介绍,只是要知道这个东西。

    参考

    https://www.objectdb.com/java/jpa/start/entity


    最新回复(0)