然后分别是使用工具类实现的对数据库的插入数据和查询数据的操作
- package com.bird.hibernate.test;
- import org.hibernate.HibernateException;
- import org.hibernate.Session;
- import org.hibernate.Transaction;
- import com.bird.domain.User;
- public class Base {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // User use = new User();
- // use.setBirthday(new Date());
- // use.setName("bird");
- // addUser(use);
- User use = getUser(1);
- System.out.println(use.getName()+" "+use.getId());
- }
- public static void addUser(User use) {
- Session s = null;
- Transaction ts = null;
- try {
- s = Hibernateutils.getSession();
- ts = s.beginTransaction();
- s.save(use);
- ts.commit();
- } catch (HibernateException e) {
- if (ts != null)
- ts.rollback();
- throw e;
- } finally {
- if (s != null)
- s.close();
- }
- }
- public static User getUser(int id) {
- Session s = null;
- try {
- s = Hibernateutils.getSession();
- User use = (User)s.get(User.class, id);
- return use;
- } catch (HibernateException e) {
- throw e;
- } finally {
- if (s != null)
- s.close();
- }
- }
- }
