开发者

java hibernate CLASS is not a bean

开发者 https://www.devze.com 2023-02-05 10:13 出处:网络
I have this simple bean name Brand. I am able to create table out of him but i cant insert data (Mysql).

I have this simple bean name Brand.

I am able to create table out of him but i cant insert data (Mysql).

The error:

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

This is the 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) {
开发者_C百科        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;
    }
}

this is how i try to insert data (and where i get the error):

    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();

this is how the table is created successfully:

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


The session factory you use to interact with the db needs to know about the entities.

In your case you need to change the code to add a Brand like this:

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();
0

精彩评论

暂无评论...
验证码 换一张
取 消