所有实体的主键都会递增

时间:2013-10-21 19:58:09

标签: java jpa

我正在用两个实体上的CRUD操作编写简单的SE应用程序。我注意到两个实体的主键都是自动递增的。当我持久保存FirstEntity的新对象时,它获得ID = 1,但是,我坚持SecondEntity并且它的ID是2但应该是1,因为没有其他类型为{{1}的实体}。出现这种情况的原因是什么?

第一个实体:

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"); } } 使用EmployeeDAO.create(Employee)来保留对象

1 个答案:

答案 0 :(得分:1)

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

strategy = GenerationType.AUTO将使hibernate(或您正在使用的任何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;