关于hibernate的问题
小弟向往数据库里面存数据,用junit测试的时候,没有通过,也没有报错,查询数据库,里面也没有数据,希望大家帮我看看。
group类:
package model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="t_group")
public class Group {
private int id;
private String name;
@Id
@GeneratedValue
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;
}
}
user类:
package model;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="t_user")
public class User {
private Group group;
private int id;
private String name;
@ManyToOne(cascade=CascadeType.ALL)
public Group getGroup() {
return group;
}
@Id
@GeneratedValue
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setGroup(Group group) {
this.group = group;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
junit测试:
package model;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class HusbandTest {
private static SessionFactory sessionFactory;
@BeforeClass
public static void beforeClass() {
new SchemaExport(new Configuration().configure()).create(false, true);
sessionFactory = new Configuration().configure().buildSessionFactory();
}
@AfterClass
public static void afterClass() {
sessionFactory.close();
}
@Test
public void testSaveUser() {
User u = new User();
u.setName("u1");
Group g = new Group();
g.setName("g1");
u.setGroup(g);
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
s.save(u);
s.getTransaction().commit();
}
public static void main(String[] args){
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
User u = new User();
u.setName("u1");
Group g = new Group();
g.setName("g1");
u.setGroup(g);
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
s.save(g);
s.save(u);
s.getTransaction().commit();
}
}
提示的信息:
16:13:54,406 INFO org.hibernate.tool.hbm2ddl.SchemaExport:234 - Running hbm2ddl schema export
16:13:54,421 DEBUG org.hibernate.tool.hbm2ddl.SchemaExport:252 - import file not found: /import.sql
16:13:54,421 INFO org.hibernate.tool.hbm2ddl.SchemaExport:262 - exporting generated schema to database
16:13:54,734 DEBUG org.hibernate.tool.hbm2ddl.SchemaExport:415 -
alter table t_user
drop
foreign key FKCB63CCB6F9B6A235
------解决方案--------------------不用setXX了吧,Hibernate保存的就是对象
------解决方案--------------------对不起,刚开始学,还有点看不懂
------解决方案--------------------