java hibernate CLASS不是bean

时间:2011-01-18 07:50:47

标签: java mysql hibernate javabeans


我有这个简单的豆名Brand 我可以创建他的表但我不能插入数据(Mysql) 错误:

Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.hibernate.beans.Brand

这是Bean:

    package com.hibernate.beans;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Brand {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long brandId;
    private String name;
    private String url;


    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public Long getBrandId() {
    return brandId;
}
public void setBrandId(Long brandId) {
    this.brandId = brandId;
}
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

这是我尝试插入数据的方式(以及我收到错误的地方):

    Brand brand = new Brand();

    brand.setName("test");
    brand.setUrl("http://www.google.com");

    Session ses = new AnnotationConfiguration().configure().buildSessionFactory().getCurrentSession();
    Transaction t = ses.beginTransaction();
    ses.save(brand);
    t.commit();

这是表成功创建的方式:

AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Brand.class);
config.configure();
new SchemaExport(config).create(true, true);

1 个答案:

答案 0 :(得分:2)

用于与数据库交互的会话工厂需要了解实体。

在您的情况下,您需要更改代码以添加这样的品牌:

Brand brand = new Brand();

brand.setName("test");
brand.setUrl("http://www.google.com");

AnnotationConfiguration c = new AnnotationConfiguration();
c.addAnnotatedClass(Brand.class);
c.configure();

Session ses = c.buildSessionFactory().getCurrentSession();

Transaction t = ses.beginTransaction();
ses.save(brand);
t.commit();