Exemplo n.º 1
0
  @Test
  public void test3Update() {
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();

    User user = (User) session.get(User.class, 1);
    user.setName("updated name");
    user.setAge(100);
    session.update(user);

    tx.commit();
    session.close();
  }
Exemplo n.º 2
0
  @Test
  public void test1Save() {
    // init data
    User user = new User();
    user.setName("foo");
    user.setAge(25);

    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    try {
      session.save(user);
      tx.commit();
    } catch (Exception e) {
      tx.rollback();
      e.printStackTrace();
    } finally {
      session.close();
    }
  }
Exemplo n.º 3
0
  @Test
  public void test6() {
    Configuration configuration =
        new Configuration()
            // 数据库连接信息
            .setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver")
            .setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate")
            .setProperty("hibernate.connection.username", "root")
            .setProperty("hibernate.connection.password", "root")
            // 方言
            .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
            .setProperty("hibernate.hbm2ddl.auto", "update")
            // 注册ORM
            .addAnnotatedClass(User.class);

    Properties props = configuration.getProperties();
    for (Map.Entry entry : props.entrySet()) {
      String key = (String) entry.getKey();
      String value = (String) entry.getValue();
      System.out.println(key);
      System.out.println(value);
    }

    SessionFactory sf = configuration.buildSessionFactory();
    Session session = sf.openSession();

    Transaction tx = session.beginTransaction();

    User user = new User();
    user.setName("foo");
    user.setAge(25);

    session.save(user);

    session.getTransaction().commit();
    session.close();
  }