加载映射文件:
(1)**.hbm.xml
SessionFactory sf = new Configuration().configure().buildSessionFactory();
(2)
SessionFactory sf = new Configuration()
.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver")
.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
.setProperty("hibernate.connection.url", "jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=latin1")
.setProperty("hibernate.connection.username", "root")
.setProperty("hibernate.connection.password", "root")
.addAnnotatedClass(Order.class)
.addAnnotatedClass(Item.class)
.buildSessionFactory();
采用第一种方法。
Session session = sf.openSession();
Transaction tran = session.beginTransaction();
添加:
User user = new User("L","Z", "JINAN");
session.save(user);
tran.commit();
查询所有:
List<User> list = session.createQuery("from User").list();
for(User user1 : list){
System.out.println(user1.getId() +" " + user1.getFirstName()+" "+user1.getLastName() + " " + user1.getAddress() + "\n");
}
查询单个:
User u = (User) session.createQuery("from User where id=:id").setInteger("id", 8).list().get(0);
System.out.println(u.getId() +" " + u.getFirstName()+" "+u.getLastName() + " " + u.getAddress() + "\n");
修改:
u.setFirstName("L");
session.update(u);// 经测试,这一步 没有一样可以修改。不知道为什么
tran.commit();
删除:
session.delete(u);
tran.commit();