0

我正在编写简单的 SE 应用程序,对两个实体进行 CRUD 操作。我注意到两个实体的主键都是自动递增的。当我坚持它的新对象时,FirstEntity它的 ID = 1 很好但是,然后我坚持SecondEntity它的 ID 是 2 但应该是一个,因为没有其他类型的实体SecondEntity。发生这种情况的原因是什么?

第一个实体:

@Entity
@NamedQueries( value = {
@NamedQuery( name = "Employee.findAll", query = "SELECT e FROM Employee e")
})
public class Employee extends AbstractModel<Long, Employee>{

@Id
@GeneratedValue( strategy = GenerationType.AUTO )
private Long id;

@Basic
@Column( name = "FIRST_NAME" )
private String firstName;
@Basic
@Column( name = "LAST_NAME" )
private String lastName;
@Basic
@Column( name = "ACCOUNT_NUMBER" )
private String accountNumber;
@Column( name = "BIRTH_DATE" )
@Temporal(TemporalType.DATE)
private Date birthDate;

@ManyToMany(cascade = CascadeType.REMOVE)
@JoinTable( name = "EMP_TASK", joinColumns = {@JoinColumn( name = "EMP_ID", referencedColumnName = "ID")},
        inverseJoinColumns = {@JoinColumn( name = "TASK_ID", referencedColumnName = "ID")})
private Set<Task> tasks = new HashSet<>();
}

第二实体:

@Entity
@NamedQueries( value = {
@NamedQuery( name = "Task.findFinished", query = "SELECT t FROM Task t where t.endDate <= :date"),
@NamedQuery( name = "Task.findActive", query = "SELECT t FROM Task t where t.startDate <= :date and :date <= t.endDate"),
@NamedQuery( name = "Task.findAll", query = "SELECT t FROM Task t")
})
public class Task extends AbstractModel<Long, Task>{

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Basic
private String name;
@Column( name = "START_DATE")
@Temporal(TemporalType.DATE)
private Date startDate;
@Column( name = "END_DATE")
@Temporal(TemporalType.DATE)
private Date endDate;

@ManyToMany( mappedBy = "tasks", cascade = CascadeType.REMOVE )
private Set<Employee> employees = new HashSet<>();
}

抽象模型:

public abstract class AbstractModel<ID extends Serializable, T extends AbstractModel<ID, T>> implements Serializable {

private Class<T> modelClass;

abstract public ID getId();

/**
 * Default construcot initializing class field.
 */
public AbstractModel(){
    modelClass = resolveModelClass();
}

/**
 * Default {2code equals(Object obj)| function for all entities
 * @param obj
 *      object to be compared
 * @return 
 *      true if object are eqaul, false otherwise
 */
@Override
public boolean equals(Object obj){
    if(!modelClass.isInstance(obj))
        return false;

    T other = modelClass.cast(obj);
    if ((this.getId() == null && other.getId() != null) || (this.getId() != null && !this.getId().equals(other.getId()))) {
        return false;
    }

    return true;
}

@Override
public int hashCode(){
    return (getId() != null ? getId().hashCode() : 0);
}

@Override
public String toString(){
    return modelClass.getName() + "[ id=" + getId() + " ]";
}

private Class<T> resolveModelClass(){
    return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
}

}

坚持方法:

private static void addNewEmployee() {
    Employee emp = new Employee();
    // setting fields of emp

    EmployeeDAO empDAO = new EmployeeDAOImpl();
    emp = empDAO.create(emp);
    if (emp != null) {
        System.out.println("New employee with ID: " + emp.getId() + " has been saved");
    } else {
        System.out.println("A problem occured while trying to persist employee entity");
    }
}

whereEmployeeDAO.create(Employee)用于EntityManager持久化对象

4

1 回答 1

1

您应该strategy = GenerationType.IDENTITY在 id-Columns 上使用。(使用表的自动增量)。

strategy = GenerationType.AUTO将使休眠(或您正在使用的任何 JPA 实现)从其 OWN 自动增量集合中选择一个数字,该集合在所有可用表中共享。

有关所有选项,请参见此处:http: //docs.oracle.com/javaee/5/api/javax/persistence/GenerationType.html

由于评论而更新:

你可以尝试使用GenerationType.Sequence

@Id
@SequenceGenerator(name="sequence1", allocationSize=1, initialValue=1)
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="sequence1")
private long id;
于 2013-10-21T20:37:48.533 回答