用到annotation 是为了省去 hbm.xml 让hibernate 帮咱们映射。 再要写很多映射类的项目中非常实用。
1.首先:搭环境,这个东西是最头疼的。我用的是hibernate3.6.0
2。写Student.java类。 写一个像helloworld一样简单的 映射类。 但是多了点东西。
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Student {
private int id;
private String name;
private String sex;
private int age;
@Id //最好放在getId()方法前面,以免方法名与变量不同时出现错误。
public int getId() {
return id;
}
/*省略其他getter 和 setter*/
}
3。然后就是测试类了 , 就用最原始的main()方法测。
public class StudentTest {
/**
*date:2010-12-28
*/
public static void main(String[] args) {
Student s = new Student();
s.setId(2);
s.setName("wang");
s.setSex("男");
s.setAge(33);
Configuration cf = new AnnotationConfiguration().configure();
SessionFactory sf = cf.buildSessionFactory();
Session session = sf.openSession();
Transaction tx ;
tx = session.beginTransaction();
session.save(s);
tx.commit();
session.close();
sf.close();
}
}
运行后就可以在MySql 中查看数据了。
还有别忘了hibernate.cfg.xml 中的 mapping 写成 <mapping class="Student" /> 。
具体实用方法可以查看hibernate 文档。 写得相当详细。