![](/img/trans.png)
[英]Is it possible to map a normal Java bean for Hibernate in a separate class / file?
[英]java hibernate CLASS is not a bean
我有這個簡單的豆子品牌。
我可以用他創建表,但不能插入數據(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);
您用於與數據庫交互的會話工廠需要了解實體。
在您的情況下,您需要更改代碼以添加這樣的品牌:
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.