Hibernate DAO将对象值设置为对象

时间:2016-06-06 11:46:23

标签: java hibernate reflection

我正在尝试在project上使用Hibernate<<如果需要所有来源,我尝试在启动时创建并保存对象播放器,我收到以下错误:

START SCRIPT!
org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.util.Date centaurus.domain.User.created] by reflection for persistent property [centaurus.domain.User#created] : User{id=0, email='test', created=Wed Jun 08 13:06:53 BST 2016}
    at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:43)
    at org.hibernate.property.access.spi.GetterFieldImpl.getForInsert(GetterFieldImpl.java:58)
    at org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValuesToInsert(AbstractEntityTuplizer.java:521)
    at org.hibernate.tuple.entity.PojoEntityTuplizer.getPropertyValuesToInsert(PojoEntityTuplizer.java:228)
    at org.hibernate.persister.entity.AbstractEntityPersister.getPropertyValuesToInsert(AbstractEntityPersister.java:4701)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:254)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:682)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
    at centaurus.service.player.PlayerDAOimpl.saveUser(PlayerDAOimpl.java:32)
    at centaurus.Dbmaintain.start(Dbmaintain.java:25)
    at restx.factory.Factory.start(Factory.java:846)
    at restx.RestxMainRouterFactory.build(RestxMainRouterFactory.java:450)
    at restx.RestxMainRouterFactory.newInstance(RestxMainRouterFactory.java:70)
    at restx.servlet.RestxMainRouterServlet.init(RestxMainRouterServlet.java:74)
    at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:519)
    at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:331)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:747)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:265)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:706)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:492)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:229)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:229)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:95)
    at org.eclipse.jetty.server.Server.doStart(Server.java:277)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at restx.server.JettyWebServer.start(JettyWebServer.java:109)
    at restx.server.JettyWebServer.startAndAwait(JettyWebServer.java:114)
    at centaurus.AppServer.main(AppServer.java:30)
Caused by: java.lang.IllegalArgumentException: Can not set java.util.Date field centaurus.domain.User.created to centaurus.domain.User
    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.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
    at java.lang.reflect.Field.get(Field.java:379)
    at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:39)
    ... 40 more
2016-06-08 13:06:53,232 [main            ] [          ] INFO  restx.monitor.MetricsConfiguration - registering Metrics JVM metrics

我已经完成了我的程序,它似乎有一个有效的对象传递了hibernate保存函数,并且它内部的某处抛出了一个错误。我已经尝试删除创建的字段,然后它会抱怨具有相同错误的字符串字段,尝试将其设置为Player对象本身。

这是我的DAOimpl.class

package centaurus.dao.user;

import centaurus.domain.User;

import centaurus.service.HibernateUtils;
import restx.factory.Component;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import javax.inject.Named;
import java.util.List;

@Component
public class UserDAOimpl implements UserDAO {
    private static HibernateUtils hibernateUtils;

    public UserDAOimpl(@Named("HibernateUtils") HibernateUtils hibernateUtils) {
        this.hibernateUtils = hibernateUtils;
    }

    public User saveUser(User user){
        Session session = hibernateUtils.getFactory().openSession();
        Transaction tx = null;
        Integer playerID = null;
        try{
            tx = session.beginTransaction();
            //playerID = (Integer) session.save(user);
            session.save(user);

            tx.commit();

        }catch (HibernateException e) {
            if (tx!=null) tx.rollback();
            e.printStackTrace();
        }finally {
            session.close();
        }
        return user;
    }

    public User getUser(int playerId){
        Session session = hibernateUtils.getFactory().openSession();
        try{
            User user = (User)session.get(User.class, playerId);
            return user;
        }catch (HibernateException e) {

        }finally {
            session.close();
        }
        return null;
    }

    public List<User> getUsers(){
        Session session = hibernateUtils.getFactory().openSession();
        List<User> list = null;
        try{
            list = session.createCriteria(User.class).list();

        }catch (HibernateException e) {

        }finally {
            session.close();
        }
        return list;
    }
}

我用google搜索和谷歌搜索了尽可能多的hibernate教程,我仍然有这个问题。我不明白为什么hibernate试图将字段设置为对象,我有我的注释。

这里想要的是我的域对象播放器:

package centaurus.domain;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;

@Entity
@Table(name="users")
public class User implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="USER_ID")
    private int id = 0;

    @Column(name="EMAIL")
    private String email = "";

    @Column(name="CREATED")
    private Date created = null;

    public User(){
        Calendar cal = Calendar.getInstance();
        this.created = cal.getTime();
    };

    public User(int id, String email, Date created) {
        this.id = id;
        this.email = email;
        this.created = created;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", email='" + email + '\'' +
                ", created=" + created +
                '}';
    }
} 

这是调用类:

package centaurus;

import centaurus.dao.user.UserDAO;
import centaurus.domain.User;
import restx.factory.AutoStartable;
import restx.factory.Component;

import javax.inject.Named;


@Component
public class DBMaintain implements AutoStartable{
    private UserDAO userDAO;

    public DBMaintain(@Named("UserDAOimpl") UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public void start(){
        System.out.println("START SCRIPT!");

        //test
        User p = new User();
        p.setEmail("test");
        userDAO.saveUser(p);

    }
}

请知道如何解决这个问题,谢谢。

编辑:(添加了sql)

CREATE TABLE Users(
    USER_ID int NOT NULL AUTO_INCREMENT,
    CREATED TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    EMAIL varchar(45) DEFAULT NULL,
    PRIMARY KEY (USER_ID)
);

EDIT添加了hibernate配置 /src/main/resources/hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection properties - Driver, URL, user, password -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost/andromeda</property>
        <property name="hibernate.connection.username">api</property>
        <property name="hibernate.connection.password">apipassword</property>
        <!-- Connection Pool Size -->
        <property name="hibernate.connection.pool_size">1</property>

        <!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
        <property name="hibernate.current_session_context_class">thread</property>

        <!-- Outputs the SQL queries, should be disabled in Production -->
        <property name="hibernate.show_sql">true</property>

        <!-- Dialect is required to let Hibernate know the Database Type, MySQL, Oracle etc
            Hibernate 4 automatically figure out Dialect from Database Connection Metadata -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>


        <mapping class="centaurus.domain.User"/>
    </session-factory>
</hibernate-configuration>

5 个答案:

答案 0 :(得分:2)

不确定这是否是答案,但我们会看到!

尝试替换

CREATED TIMESTAMP DEFAULT CURRENT_TIMESTAMP

CREATED DATETIME DEFAULT CURRENT_DATETIME,

在SQL中查看Timestamp和Datetime之间的区别是 TIMESTAMP值从当前时区转换为UTC进行存储,并从UTC转换回当前时区以进行检索。 (这仅适用于TIMESTAMP数据类型,而不适用于其他类型,例如DATETIME。) 如果存储TIMESTAMP值,然后更改时区并检索该值,则检索的值与您存储的值不同。 TimeStamp MySQL

虽然 DATETIME表示日期(在日历中找到)和时间(可以在挂钟上观察到),

由于您无法将Java Date存储到SQL TIMESTAMP对象中,因此请将SQL TIMESTAMP更改为DATETIME或更改

private Date created;

private Timestamp created;

//And convert your Date to TimeStamp
public User(){
    Date date = new Date();
    created = new Timestamp(date .getTime());
}

希望这有帮助!

答案 1 :(得分:1)

从包centaurus中删除User类

为什么?

在AppServer.main上你有:

  

System.setProperty(&#34; restx.app.package&#34;,&#34; centaurus&#34;);

这将使restx重新编译centaurus包内的所有内容并使用这个重新编译的类,但显然hibernate从原始类中检索字段,而不是从重新编译的字段中检索字段

这是真正重要的堆栈跟踪:

Caused by: java.lang.IllegalArgumentException: Can not set java.util.Date field centaurus.domain.User.created to centaurus.domain.User
    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.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
    at java.lang.reflect.Field.get(Field.java:379)

JVM抛出一个异常,因为它不能在User类(由restx编译的restx加载)中使用Field(由原始编译中的hibernate检索)

答案 2 :(得分:0)

Hibernate无法转换为joda DateTime开箱即用。尝试使用

注释您的列
@Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")

请参阅here以供参考。

答案 3 :(得分:0)

看起来这是这个版本的Hibernate中的一个错误

HHH-10618

尝试使用另一个。

答案 4 :(得分:0)

您的日期字段必须注释如下:

<img src="smiley.gif" alt="Smiley face" height="42" width="42">

请务必重命名字段的列和名称以匹配您的项目。