命名类型 [com.go_task.entity.User@5b4d25e7] 未实现 BasicType 也未实现 UserType

huangapple go评论76阅读模式
英文:

Named type [com.go_task.entity.User@5b4d25e7] did not implement BasicType nor UserType

问题

以下是翻译好的代码部分:

User.java

package com.go_task.entity;

import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

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

    @Id
    @GeneratedValue
    private int id;

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

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

    @Column(name = "password")
    private String password;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private List<Task> tasks = new ArrayList<>();

    // 构造函数和 getter、setter 方法

    // ...
}

Task.java

package com.go_task.entity;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "tasks")
public class Task implements Serializable {

    @Id
    @GeneratedValue
    private int id;

    @Column(name = "title")
    private String title;

    @ManyToOne
    private User user;

    // 构造函数和 getter、setter 方法

    // ...
}

HibernateUtil.java class

package com.go_task.database;

import com.go_task.entity.Task;
import com.go_task.entity.User;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

    private static SessionFactory sessionFactory = null;

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            try {
                Configuration configuration = new Configuration();
                configuration.configure("db/hibernate.cfg.xml");
                configuration.addAnnotatedClass(User.class).addAnnotatedClass(Task.class);

                ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                        .applySettings(configuration.getProperties()).build();
                sessionFactory = configuration.buildSessionFactory(serviceRegistry);
                return sessionFactory;

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sessionFactory;
    }
}

Test.java

package com.go_task.dao;

import com.go_task.database.HibernateUtil;
import com.go_task.entity.User;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Test {

    public static void main(String[] args) {
        User user1 = new User("Name", "email", "pass");

        Transaction transaction = null;

        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            transaction = session.beginTransaction();
            session.save(user1);
            transaction.commit();
        } catch (Exception exception) {
            if (transaction != null) transaction.rollback();
            exception.printStackTrace();
        }
    }
}

hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Hibernate 配置信息 -->

        <!-- ... -->
    </session-factory>
</hibernate-configuration>

当我尝试运行Test.java类时,出现了下面的异常:

java.lang.IllegalArgumentException: Named type [com.go_task.entity.User@5b4d25e7] did not implement BasicType nor UserType
	at org.hibernate.boot.model.TypeDefinition.createReusableResolution(TypeDefinition.java:213)
	at org.hibernate.boot.model.TypeDefinition.resolve(TypeDefinition.java:113)
	at org.hibernate.mapping.BasicValue.interpretExplicitlyNamedType(BasicValue.java:382)
	at org.hibernate.mapping.BasicValue.resolve(BasicValue.java:168)
	at org.hibernate.mapping.BasicValue.getType(BasicValue.java:155)
	at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:453)
	at org.hibernate.mapping.Property.isValid(Property.java:223)
	at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:624)
	at org.hibernate.mapping.RootClass.validate(RootClass.java:267)
	at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:353)
	at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:452)
	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:730)
	at com.go_task.database.HibernateUtil.getSessionFactory(HibernateUtil.java:29)
	at com.go_task.dao.Test.main(Test.java:15)

Process finished with exit code 0
英文:

I have 2 models. One is the User model and another is the Task model. I'm trying to obtain "one to many" bidirectional relations. But even before doing that when I'm trying to create a user from Test.java class. I'm having an exception.

Named type [com.go_task.entity.User@5b4d25e7] did not implement BasicType nor UserType

How can I fix this?

User.java

package com.go_task.entity;


import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


@Entity
@Table(name = &quot;users&quot;)
public class User implements Serializable {

    @Id
    @GeneratedValue
    private int id;

    @Column(name = &quot;name&quot;)
    private String name;

    @Column(name = &quot;email&quot;)
    private String email;

    @Column(name = &quot;password&quot;)
    private String password;

    @OneToMany(mappedBy = &quot;user&quot;, cascade = CascadeType.ALL)
    private List&lt;Task&gt; tasks = new ArrayList&lt;&gt;();

    public User() {}

    public User(int id, String name, String email, String password) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.password = password;
    }

    public User(String name, String email, String password) {
        this.name = name;
        this.email = email;
        this.password = password;
    }

    @Id
    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List&lt;Task&gt; getTasks() {
        return tasks;
    }

    public void setTasks(List&lt;Task&gt; tasks) {
        this.tasks = tasks;
    }

    public void addTask(Task task) {
        tasks.add(task);
        task.setUser(this);
    }

    public void removeTask(Task task) {
        tasks.remove(task);
        task.setUser(this);
    }
}

Task.java

package com.go_task.entity;


import javax.persistence.*;
import java.io.Serializable;


@Entity
@Table(name = &quot;tasks&quot;)
public class Task implements Serializable {

    @Id
    @GeneratedValue
    private int id;

    @Column(name = &quot;title&quot;)
    private String title;

    @ManyToOne
    private User user;

    public Task() {}

    public Task(int id, String title) {
        this.id = id;
        this.title = title;
    }

    public Task(String title) {
        this.title = title;
    }

    @Id
    public int getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

HibernateUtil.java class

package com.go_task.database;

import com.go_task.entity.Task;
import com.go_task.entity.User;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

    private static SessionFactory sessionFactory = null;

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            try {
                Configuration configuration = new Configuration();
                configuration.configure(&quot;db/hibernate.cfg.xml&quot;);
                configuration.addAnnotatedClass(User.class).addAnnotatedClass(Task.class);

                ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                        .applySettings(configuration.getProperties()).build();
                System.out.println(&quot;Hibernate Java Config serviceRegistry created&quot;);
                sessionFactory = configuration.buildSessionFactory(serviceRegistry);
                System.out.println(sessionFactory);
                return sessionFactory;

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sessionFactory;
    }
}

Test.java

package com.go_task.dao;

import com.go_task.database.HibernateUtil;
import com.go_task.entity.User;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Test {

    public static void main(String[] args) {
        User user1 = new User(&quot;Name&quot;, &quot;email&quot;, &quot;pass&quot;);

        Transaction transaction = null;

        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            transaction = session.beginTransaction();
            session.save(user1);
            transaction.commit();
        } catch (Exception exception) {
            if (transaction != null) transaction.rollback();
            exception.getStackTrace();
        }
    }
}

hibernate.cfg.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC &quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot; &quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;&gt;
&lt;hibernate-configuration&gt;
    &lt;session-factory&gt;
        &lt;property name=&quot;hibernate.connection.driver_class&quot;&gt;com.mysql.cj.jdbc.Driver&lt;/property&gt;
        &lt;property name=&quot;hibernate.connection.url&quot;&gt;jdbc:mysql://localhost:3306/otm_dm&lt;/property&gt;
        &lt;property name=&quot;hibernate.connection.username&quot;&gt;root&lt;/property&gt;
        &lt;property name=&quot;hibernate.connection.password&quot;&gt;root&lt;/property&gt;
        &lt;property name=&quot;hibernate.dialect&quot;&gt;org.hibernate.dialect.MySQL5Dialect&lt;/property&gt;
        &lt;property name=&quot;show_sql&quot;&gt;false&lt;/property&gt;
    &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;

When I'm trying to run Test.java class, I'm having the exception below:

java.lang.IllegalArgumentException: Named type [com.go_task.entity.User@5b4d25e7] did not implement BasicType nor UserType
	at org.hibernate.boot.model.TypeDefinition.createReusableResolution(TypeDefinition.java:213)
	at org.hibernate.boot.model.TypeDefinition.resolve(TypeDefinition.java:113)
	at org.hibernate.mapping.BasicValue.interpretExplicitlyNamedType(BasicValue.java:382)
	at org.hibernate.mapping.BasicValue.resolve(BasicValue.java:168)
	at org.hibernate.mapping.BasicValue.getType(BasicValue.java:155)
	at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:453)
	at org.hibernate.mapping.Property.isValid(Property.java:223)
	at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:624)
	at org.hibernate.mapping.RootClass.validate(RootClass.java:267)
	at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:353)
	at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:452)
	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:730)
	at com.go_task.database.HibernateUtil.getSessionFactory(HibernateUtil.java:29)
	at com.go_task.dao.Test.main(Test.java:15)

Process finished with exit code 0

答案1

得分: 2

添加带有连接列名称和引用列名称的@JoinColumn

@Entity
@Table(name = "tasks")
public class Task implements Serializable {

    // ...

    @ManyToOne
    @JoinColumn(name = "user_id", referencedColumnName = "id")
    private User user;
    
    // ...
}
英文:

Add @JoinColumn with join column name and reference column name.

@Entity
@Table(name = &quot;tasks&quot;)
public class Task implements Serializable {

    // ...

    @ManyToOne
    @JoinColumn(name = &quot;user_id&quot;, referencedColumnName = &quot;id&quot;)
    private User user;
    
    // ...
}

答案2

得分: 0

我在getTasks()方法前添加了@OneToMany注解,并在getUser()方法前添加了@ManyToOne注解。之后问题得到解决,现在它正常工作了。但是关于异常还不太清楚。

还有一件事,我使用的是Hibernate版本6 alpha!

英文:

I have added @OneToMany annotation before the getTasks() method and @ManyToOne annotation before getUser() method. After that it solved my problem. It's working now. But not clear about the exception though.

One more thing, I have used Hibernate Version 6 alpha!

huangapple
  • 本文由 发表于 2020年9月25日 22:45:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/64066402.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定