проблема типа столбца в спящем режиме (MySql) - PullRequest
1 голос
/ 13 февраля 2011


Я получаю это исключение:
Can not set int field com.affiliates.hibernate.Employee.employeeId to java.lang.Integer
пытаясь получить результаты от creteria:

Transaction t = getSession().beginTransaction();

DetachedCriteria c = DetachedCriteria.forClass(Affiliate.class);
c.add(Restrictions.eq("employee", 1));
List l = c.getExecutableCriteria(getSession()).list();
t.commit();

выполнение запроса в базе данных с выдачей результатов.

Это бобы моего филиала и сотрудника:

@Entity(name="AFFILIATE")
public class Affiliate extends HibernateBean{ 
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY) 
    @Column(name="AFFILIATE_ID")
    private int id;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="EMPLOYEE_ID")
    private Employee employee;
        //other memebers + get and set
}

@Entity(name="EMPLOYEE")
public class Employee extends HibernateBean implements ILoginAble{
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="EMPLOYEE_ID")
    private int employeeId;
        //other memebers + get and set
}

это таблицы:

Create Table
CREATE TABLE `AFFILIATE` (
  `AFFILIATE_ID` int(11) NOT NULL AUTO_INCREMENT,
  `EMPLOYEE_ID` int(11) DEFAULT NULL,
  PRIMARY KEY (`AFFILIATE_ID`),

  KEY `fk_AFFILIATE_EMPLOYEE1` (`EMPLOYEE_ID`),
  CONSTRAINT `fk_AFFILIATE_AFFILIATE1` FOREIGN KEY (`PARENT_ID`) REFERENCES `AFFILIATE` (`AFFILIATE_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_AFFILIATE_EMPLOYEE1` FOREIGN KEY (`EMPLOYEE_ID`) REFERENCES `EMPLOYEE` (`EMPLOYEE_ID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_bin

CREATE TABLE `EMPLOYEE` (
  `EMPLOYEE_ID` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`EMPLOYEE_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin

Это полное исключение:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select this_.AFFILIATE_ID as AFFILIATE1_8_2_, this_.EMAIL as EMAIL8_2_, this_.EMPLOYEE_ID as EMPLOYEE6_8_2_, this_.name as name8_2_, this_.PARENT_ID as PARENT7_8_2_, this_.PASSWORD as PASSWORD8_2_, this_.USER_NAME as USER5_8_2_, employee2_.EMPLOYEE_ID as EMPLOYEE1_2_0_, employee2_.EMAIL as EMAIL2_0_, employee2_.FIRST_NAME as FIRST3_2_0_, employee2_.IS_ACTIVE as IS4_2_0_, employee2_.LAST_NAME as LAST5_2_0_, employee2_.PASSWORD as PASSWORD2_0_, employee2_.REG_DATE as REG7_2_0_, employee2_.USER_NAME as USER8_2_0_, affiliate3_.AFFILIATE_ID as AFFILIATE1_8_1_, affiliate3_.EMAIL as EMAIL8_1_, affiliate3_.EMPLOYEE_ID as EMPLOYEE6_8_1_, affiliate3_.name as name8_1_, affiliate3_.PARENT_ID as PARENT7_8_1_, affiliate3_.PASSWORD as PASSWORD8_1_, affiliate3_.USER_NAME as USER5_8_1_ from AFFILIATE this_ left outer join EMPLOYEE employee2_ on this_.EMPLOYEE_ID=employee2_.EMPLOYEE_ID left outer join AFFILIATE affiliate3_ on this_.PARENT_ID=affiliate3_.AFFILIATE_ID where this_.EMPLOYEE_ID=?
Exception in thread "main" org.hibernate.PropertyAccessException: could not get a field value by reflection getter of com.affiliates.hibernate.Employee.employeeId
    at org.hibernate.property.DirectPropertyAccessor$DirectGetter.get(DirectPropertyAccessor.java:58)
    at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:206)
    at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:3619)
    at org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:3335)
    at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:204)
    at org.hibernate.engine.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:241)
    at org.hibernate.type.EntityType.getIdentifier(EntityType.java:430)
    at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:110)
    at org.hibernate.loader.Loader.bindPositionalParameters(Loader.java:1728)
    at org.hibernate.loader.Loader.bindParameterValues(Loader.java:1699)
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1589)
    at org.hibernate.loader.Loader.doQuery(Loader.java:696)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
    at org.hibernate.loader.Loader.doList(Loader.java:2228)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2125)
    at org.hibernate.loader.Loader.list(Loader.java:2120)
    at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:118)
    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1596)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:342)
    at $Proxy14.list(Unknown Source)
    at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:306)
    at com.affiliates.dao.BaseApplicationDao.getAll(BaseApplicationDao.java:43)
    at com.affiliates.api.AffiliatesApi.getAll(AffiliatesApi.java:39)
    at com.affiliates.api.AffiliatesAPITest.getAll(AffiliatesAPITest.java:22)
    at com.affiliates.api.AffiliatesAPITest.main(AffiliatesAPITest.java:15)
Caused by: java.lang.IllegalArgumentException: Can not set int field com.affiliates.hibernate.Employee.employeeId to java.lang.Integer
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:164)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:168)
    at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:55)
    at sun.reflect.UnsafeIntegerFieldAccessorImpl.getInt(UnsafeIntegerFieldAccessorImpl.java:56)
    at sun.reflect.UnsafeIntegerFieldAccessorImpl.get(UnsafeIntegerFieldAccessorImpl.java:36)
    at java.lang.reflect.Field.get(Field.java:376)
    at org.hibernate.property.DirectPropertyAccessor$DirectGetter.get(DirectPropertyAccessor.java:55)

... 28 more

Ответы [ 2 ]

3 голосов
/ 13 февраля 2011

Проблема, вероятно, с этим ограничением:

c.add(Restrictions.eq("employee", 1));

Это означает: «убедитесь, что поле сотрудника экземпляра Affiliate равно 1».

Но поле сотрудника класса Affiliate не является ни int, ни Integer. Это сотрудник.

Измените ваше ограничение на

c.add(Restrictions.eq("employee.employeeId", 1));

Я также удивлен каскадным типом отношений между сотрудником и партнером. У сотрудника много партнеров, но когда вы удаляете одного из партнеров, вы хотите, чтобы сотрудник был удален. Я сомневаюсь, что это работает (у вас будут нарушения ограничений).

0 голосов
/ 13 февраля 2011

Измените все ваши поля примитивных типов на Типы объектов. В вашем случае int должно быть Integer.

как:

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="EMPLOYEE_ID")
private Integer employeeId;

// don't forget to change the corresponding getters and setters.

Хорошего дня
Томас

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...