コード例 #1
0
  /**
   * With delete-orphan cascade. The cascade=”delete-orphan” is declared in ‘billingDetails’ to
   * enable the delete orphan cascade effect. When you save or update the User, it will remove those
   * ‘billingDetails’ which already mark as removed.
   *
   * <p>In short, delete-orphan allow parent table to delete few records (delete orphan) in its
   * child table.
   */
  public void /*test*/ BillingDetailsWithDeleteOrphanCascade() throws Exception {
    LogHelper.disableLogging();
    User u1 = new User("Christian", "Bauer", "turin", "abc123", "*****@*****.**");
    u1.setAddress(new Address("Foo", "12345", "Bar"));
    u1.setAdmin(true);

    HibernateUtil.getSession().save(u1);

    BillingDetails ccOne =
        new CreditCard(
            "Christian  Bauer", u1, "1234567890", CreditCardType.MASTERCARD, "10", "2005");
    u1.addBillingDetails(ccOne);

    HibernateUtil.getSession().save(ccOne);

    HibernateUtil.getSession().flush();

    UserDAO userDAO = new UserDAO();
    User user = userDAO.loadUserById(1l, false);

    Set details = user.getBillingDetails();

    for (Object detail : details) {
      LogHelper.setLogging("org.hibernate.SQL", Level.DEBUG);

      user.getBillingDetails().remove(detail);
      user.setDefaultBillingDetails(null);

      LogHelper.disableLogging();
    }

    LogHelper.setLogging("org.hibernate.SQL", Level.DEBUG);
    HibernateUtil.getSession().saveOrUpdate(u1);
    HibernateUtil.getSession().flush();
  }
コード例 #2
0
  public void /*test*/ LoadUserWithBillingDetails() {
    System.out.println("******************** testLoadUserWithBillingDetails ********************");
    UserDAO userDAO = new UserDAO();
    User user = userDAO.loadUserById(1l, false);

    Set<BillingDetails> billingDetails = user.getBillingDetails();
    Iterator<BillingDetails> billingIterator = billingDetails.iterator();

    while (billingIterator.hasNext()) {
      BillingDetails details = billingIterator.next();
      if (details instanceof BankAccount) {
        BankAccount account = (BankAccount) details;
        assertEquals("FooBar Rich Bank", account.getBankName());
        assertEquals("234234234234", account.getNumber());
      }

      if (details instanceof CreditCard) {
        CreditCard cc = (CreditCard) details;
        assertEquals("1234567890", cc.getNumber());
      }

      if (details instanceof HibernateProxy) {
        HibernateProxy proxy = (HibernateProxy) details;
        Object proxyImpl = proxy.getHibernateLazyInitializer().getImplementation();
        if (proxyImpl instanceof CreditCard) {
          CreditCard cc = (CreditCard) proxyImpl;
          assertEquals("1234567890", cc.getNumber());
        } else {
          fail("Proxy is not a CreditCard");
        }
      }
    }

    BillingDetails defaultBillingDetails = user.getDefaultBillingDetails();
    if (defaultBillingDetails instanceof HibernateProxy) {
      HibernateProxy proxy = (HibernateProxy) defaultBillingDetails;
      Object proxyImpl = proxy.getHibernateLazyInitializer().getImplementation();
      if (proxyImpl instanceof CreditCard) {
        CreditCard cc = (CreditCard) proxyImpl;
        assertEquals("1234567890", cc.getNumber());
      } else {
        fail("Proxy is not a CreditCard");
      }
    } else {
      fail("DefaultBillingDetails is not a proxy");
    }

    // HibernateUtil.closeSession();
    BillingDetailsDAO billingDetailsDAO = new BillingDetailsDAO();
    BillingDetails billingDetails1 = billingDetailsDAO.getBillingDetailsById(1l, false);
    assertNotNull(billingDetails1);
    assertTrue(billingDetails1.getUser() == user);

    user.removeBillingDetails(billingDetails1);
    HibernateUtil.getSession().flush();

    // BillingDetails billingDetails2 = billingDetailsDAO.loadBillingDetailsById(1l, false);
    BillingDetails billingDetails2 = billingDetailsDAO.getBillingDetailsById(1l, false);
    assertNull(billingDetails2);
  }
コード例 #3
0
ファイル: UserDAO.java プロジェクト: alex93306/training
  public void makeTransient(User user) throws InfrastructureException {

    try {
      HibernateUtil.getSession().delete(user);
    } catch (HibernateException ex) {
      throw new InfrastructureException(ex);
    }
  }
コード例 #4
0
ファイル: UserDAO.java プロジェクト: alex93306/training
  public void makePersistent(User user) throws InfrastructureException {

    try {
      HibernateUtil.getSession().saveOrUpdate(user);
    } catch (HibernateException ex) {
      throw new InfrastructureException(ex);
    }
  }
コード例 #5
0
ファイル: UserDAO.java プロジェクト: alex93306/training
  public Collection findAll() throws InfrastructureException {

    Collection users;
    try {
      users = HibernateUtil.getSession().createCriteria(User.class).list();
    } catch (HibernateException ex) {
      throw new InfrastructureException(ex);
    }
    return users;
  }
コード例 #6
0
ファイル: UserDAO.java プロジェクト: alex93306/training
  public Collection findByExample(User exampleUser) throws InfrastructureException {

    Collection users;
    try {
      Criteria crit = HibernateUtil.getSession().createCriteria(User.class);
      users = crit.add(Example.create(exampleUser)).list();
    } catch (HibernateException ex) {
      throw new InfrastructureException(ex);
    }
    return users;
  }
コード例 #7
0
  /**
   * With save-update cascade. The cascade=”save-update” is declared in ‘BillingDetails’ to enable
   * the save-update cascade effect..
   */
  public void /*test*/ BillingDetailsCascadeSaveUpdate() {
    User u1 = new User("Christian", "Bauer", "turin", "abc123", "*****@*****.**");
    u1.setAddress(new Address("Foo", "12345", "Bar"));
    u1.setAdmin(true);

    BillingDetails ccOne =
        new CreditCard(
            "Christian  Bauer", u1, "1234567890", CreditCardType.MASTERCARD, "10", "2005");
    u1.addBillingDetails(ccOne);

    HibernateUtil.getSession().save(u1);
  }
コード例 #8
0
  public void /*test*/ AddNewProperty() {
    System.out.println("******************* testAddNewProperty ********************");
    PersistentClass userMapping = HibernateUtil.getClassMapping(User.class);

    Column column = new Column();
    column.setName("MOTTO");
    column.setNullable(false);
    column.setUnique(true);
    column.setSqlType("VARCHAR");
    userMapping.getTable().addColumn(column);

    SimpleValue value = new SimpleValue();
    value.setTable(userMapping.getTable());
    value.addColumn(column);
    value.setTypeName("string");

    Property prop = new Property();
    prop.setValue(value);
    prop.setName("motto");
    prop.setPropertyAccessorName("field");
    prop.setNodeName(prop.getName());
    userMapping.addProperty(prop);

    HibernateUtil.rebuildSessionFactory();

    ClassMetadata metadata = HibernateUtil.getClassMetadata(User.class);
    String[] propNames = metadata.getPropertyNames();
    boolean mottoFound = false;
    for (int i = 0; i < propNames.length; i++) {
      String propName = propNames[i];
      if (propName.equalsIgnoreCase("motto")) {
        mottoFound = true;
        break;
      }
    }

    assertTrue(mottoFound);
  }
コード例 #9
0
ファイル: UserDAO.java プロジェクト: alex93306/training
  public User getUserById(Long userId, boolean lock) throws InfrastructureException {

    Session session = HibernateUtil.getSession();
    User user = null;
    try {
      if (lock) {
        user = (User) session.load(User.class, userId, LockMode.UPGRADE);
      } else {
        user = (User) session.load(User.class, userId);
      }
    } catch (HibernateException ex) {
      throw new InfrastructureException(ex);
    }
    return user;
  }
コード例 #10
0
  /**
   * fetch=”subselect” or @Fetch(FetchMode.SUBSELECT).
   *
   * <p>This fetching strategy is enable all its related collection in a sub select statement. Let
   * see the same query again.
   *
   * <p>With “subselect” enabled, it will create two select statements.
   *
   * <p>1. Select statement to retrieve all the Stock records.
   *
   * <p>2. Select all its related collections in a sub select query.
   */
  @org.junit.Test
  public void /*test*/ UserBatchItems() {
    System.out.println("******************* testUserBatchItems ********************");
    Session session = HibernateUtil.getSession();
    List<User> list = session.createQuery("from User").list();

    for (User user : list) {
      Set items = user.getItems();

      for (Iterator iter = items.iterator(); iter.hasNext(); ) {
        Item item = (Item) iter.next();
        assertNotNull(item.getId());
        assertNotNull(item.getName());
      }
    }
  }
コード例 #11
0
  public void /*test*/ UserWithItems() throws Exception {
    System.out.println("******************** testUserWithItems ********************");

    UserDAO userDAO = new UserDAO();
    assertTrue(userDAO.findAll().size() > 0);

    User user = new User();
    user.setFirstname("Christian");
    user.setAdmin(true);
    user.clearCreatedDate();

    Collection users = userDAO.findByExample(user);

    assertNotNull(users);
    Object[] userArr = users.toArray();
    assertTrue(userArr.length > 0);
    assertTrue(userArr[0] instanceof User);

    User christian = (User) userArr[0];
    assertNotNull(christian.getId());

    Set items = christian.getItems();
    Item item = (Item) items.toArray()[0];
    assertNotNull(item.getId());

    Calendar inThreeDays = GregorianCalendar.getInstance();
    inThreeDays.roll(Calendar.DAY_OF_YEAR, 3);
    Item newItem =
        new Item(
            "Item One",
            "An item in the carsLuxury category.",
            christian,
            new MonetaryAmount(new BigDecimal("1.99"), Currency.getInstance(Locale.US)),
            new MonetaryAmount(new BigDecimal("50.33"), Currency.getInstance(Locale.US)),
            new Date(),
            inThreeDays.getTime());

    christian.addItem(newItem);

    ItemDAO itemDAO = new ItemDAO();
    itemDAO.makePersistent(newItem);

    HibernateUtil.commitTransaction();
  }
コード例 #12
0
ファイル: UserDAO.java プロジェクト: alex93306/training
 public UserDAO() {
   HibernateUtil.beginTransaction();
 }
コード例 #13
0
 protected void tearDown() throws Exception {
   HibernateUtil.closeSession();
 }