Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Не узнаваемые ключи сущностей, Проблемма в Eclipse 
:(
    Опции темы
ShurikA
Дата 6.11.2009, 21:52 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Зануда
***


Профиль
Группа: Завсегдатай
Сообщений: 1364
Регистрация: 29.10.2005
Где: Канада

Репутация: нет
Всего: 3



Я решил переползти с NetBeans на Eclipse и вроде как не удачно, кроме одной проблеммы:
Есть несколько сущностей с composite primary key.
На пример:
Код

package persistence.entity.hr;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Id;
/**
 *
 * @author ShurikAg
 */
public class EmployeeId implements Serializable {
    private static final long serialVersionUID = 1L;
    /**
     * Employee ID within company
     */
    @Id
    @Basic(optional = false)
    @Column(name = "id", nullable = false, insertable = true, updatable = false)
    public Integer id;
    /**
     * Company ID the employee is working in.
     */
    @Id
    @Basic(optional = false)
    @Column(name = "companyId", nullable = false, insertable = true, updatable = true)
    public Integer companyId;
    public EmployeeId() {
    }
    public EmployeeId(Integer id, Integer companyId) {
        this.id = id;
        this.companyId = companyId;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public Integer getCompanyId() {
        return companyId;
    }
    public void setCompanyId(Integer companyId) {
        this.companyId = companyId;
    }
    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        hash += (companyId != null ? companyId.hashCode() : 0);
        return hash;
    }
    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof EmployeeId)) {
            return false;
        }
        EmployeeId other = (EmployeeId) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id)) ||
                (this.companyId == null && other.companyId != null) ||
                (this.companyId != null && !this.companyId.equals(other.companyId))) {
            return false;
        }
        return true;
    }
    @Override
    public String toString() {
        return "hr.EmployeeId[id=" + id + ", companyId=" + companyId + "]";
    }
}


Код

package persistence.entity.hr;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import persistence.entity.EntitySuperClass;
import persistence.entity.hr.config.EmployeePosition;
import persistence.entity.hr.config.EmployeeType;
/**
 *
 * @author ShurikAg
 */
@Entity
@IdClass(EmployeeId.class)
@Table(name = "Employee", catalog = "timesheet", schema = "")
public class Employee extends EntitySuperClass implements Serializable {
    private static final long serialVersionUID = 1L;
    /**
     * Employee ID within company
     */
    @Id
    @Basic(optional = false)
    @Column(name = "id", nullable = false, insertable = true, updatable = false)
    private Integer id;
    /**
     * Company ID the employee is working in.
     */
    @Id
    @Basic(optional = false)
    @Column(name = "companyId", nullable = false, insertable = true, updatable = true)
    private Integer companyId;
    /**
     * User login ID
     */
    @Basic(optional = false)
    @Column(name = "userId", nullable = false, insertable = true, updatable = false)
    private Integer userId;
    /**
     * Organization unit the employee related to
     */
    @Basic(optional = false)
    @Column(name = "organizationId", nullable = false, insertable = true, updatable = true)
    private Integer organizationId;
    /**
     * Position ID of this employee
     */
    @Basic(optional = false)
    @Column(name = "positionId", nullable = false, insertable = true, updatable = true)
    private Integer positionId;
    /**
     * Employee type ID
     */
    @Basic(optional = false)
    @Column(name = "employeeTypeId", nullable = false, insertable = true, updatable = true)
    private Integer employeeTypeId;
    /**
     * First name of employee
     */
    @Basic(optional = false)
    @Column(name = "firstname", nullable = false, insertable = true, updatable = true)
    private String firstname;
    /**
     * Last name of employee
     */
    @Basic(optional = false)
    @Column(name = "lastname", nullable = false, insertable = true, updatable = true)
    private String lastname;
    /**
     * Manager ID of this employee
     */
    @Basic(optional = true)
    @Column(name = "managerId", nullable = true, insertable = true, updatable = true)
    private Integer managerId;
    /**
     * Percentage of part time in case that the employee is a part time
     */
    @Basic(optional = true)
    @Column(name = "partTimePercent", nullable = true, insertable = true, updatable = true)
    private Integer partTimePercent;
    /**
     * Entity of employee type
     */
    @ManyToOne
    @JoinColumn(name = "employeeTypeId", referencedColumnName = "id")
    private EmployeeType employeeType;
    /**
     * Entity of employee type
     */
    @ManyToOne
    @JoinColumn(name = "positionId", referencedColumnName = "id")
    private EmployeePosition employeePosition;
    /**
     * Direct manager of an employee
     */
    @ManyToOne
    @JoinColumns({
        @JoinColumn(name = "managerId", referencedColumnName = "id"),
        @JoinColumn(name = "companyId", referencedColumnName = "companyId")
    })
    private Employee directManager;
    /**
     * Direct reporters to manager.
     */
    @OneToMany(mappedBy = "directManager")
    private Collection<Employee> directs;
    public Employee getDirectManager() {
        return directManager;
    }
    public void setDirectManager(Employee directManager) {
        this.directManager = directManager;
    }
    public Collection<Employee> getDirects() {
        return directs;
    }
    public void setDirects(Collection<Employee> directs) {
        this.directs = directs;
    }
    public EmployeePosition getEmployeePosition() {
        return employeePosition;
    }
    public void setEmployeePosition(EmployeePosition employeePosition) {
        this.employeePosition = employeePosition;
    }
    public EmployeeType getEmployeeType() {
        return employeeType;
    }
    public void setEmployeeType(EmployeeType employeeType) {
        this.employeeType = employeeType;
        this.employeeTypeId = employeeType.getId();
    }
    public Integer getEmployeeTypeId() {
        return employeeTypeId;
    }
    public void setEmployeeTypeId(Integer employeeTypeId) {
        this.employeeTypeId = employeeTypeId;
    }
    public Integer getCompanyId() {
        return companyId;
    }
    public void setCompanyId(Integer companyId) {
        this.companyId = companyId;
    }
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public Integer getManagerId() {
        return managerId;
    }
    public void setManagerId(Integer managerId) {
        this.managerId = managerId;
    }
    public Integer getOrganizationId() {
        return organizationId;
    }
    public void setOrganizationId(Integer organizationId) {
        this.organizationId = organizationId;
    }
    public Integer getPartTimePercent() {
        return partTimePercent;
    }
    public void setPartTimePercent(Integer partTimePercent) {
        this.partTimePercent = partTimePercent;
    }
    public Integer getPositionId() {
        return positionId;
    }
    public void setPositionId(Integer positionId) {
        this.positionId = positionId;
    }
    public Integer getUserId() {
        return userId;
    }
    public void setUserId(Integer userId) {
        this.userId = userId;
    }
//    @Override
//    public int hashCode() {
//        int hash = 0;
//        hash += (id != null ? id.hashCode() : 0);
//        return hash;
//    }
//
//    @Override
//    public boolean equals(Object object) {
//        // TODO: Warning - this method won't work in the case the id fields are not set
//        if (!(object instanceof Employee)) {
//            return false;
//        }
//        Employee other = (Employee) object;
//        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
//            return false;
//        }
//        return true;
//    }
//
//    @Override
//    public String toString() {
//        return "hr.Employee[id=" + id + "]";
//    }
}


Все сущности такого типа не проходят валидацию в Eclipse. Eclipse сообщает: @Entity does not have primary key

(могу ошибаться в точных словах, пишу по памяти).

В чём может быть проблемма?


--------------------
Если долго мучиться, что нибудь получится...
user posted image
PM MAIL WWW ICQ Skype   Вверх
Joss
Дата 7.11.2009, 11:28 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 103
Регистрация: 19.3.2006

Репутация: нет
Всего: 1



Хм, а что делают аннотации @Id, @Basic, @Column в классе первичного ключа? Они используются на полях/методах Entity.
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   tux
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java EE (J2EE) и Spring | Следующая тема »


 




[ Время генерации скрипта: 0.0513 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.