3

I am creating a java application which uses ObjectDB to create and maintain a set of databases. I'm currently trying to implement a DB to store user objects consisting of username and password strings. On a JFrame/swing class I have a button for creating new users, when this button is clicked, I want the following to happen:

  1. Create (or connect to) database
  2. Search the database to see if a user object exists with supplied username
  3. if user already exists show a dialog message, otherwise create the user

However, when this button is clicked I get a 'User not found' error on the line which uses the results from the query object. I'm pretty sure it's because I have an empty database, however I want the code to work for the first time the program is ran, so it needs to handle an empty database. I've tried changing the code to create a new user before the query is first run, then the code works how I want it to each time the button is clicked, and it can detect whether or not a new user needs to be created.

I tried to create a 'default' or 'admin' type user so the search would work, however this means a repeat 'default' user will be created every time the program is ran, which is obviously an unwanted feature, and I can't do a query to check if the database is empty (so I could only create the default user on the first run of the program), because that is the problem I was having in the first place!

So, to anyone experienced with ObjectDB, is there a way I can handle the case where an empty database is searched?

Here's the relevant parts of my code:

public class FrameLogIn extends JFrame {

private JPanel contentPane;
private String username;
char[] password;
private static EntityManager em;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                FrameLogIn frame = new FrameLogIn();
                frame.setVisible(true);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public FrameLogIn() {

    EntityManagerFactory emf = 
            Persistence.createEntityManagerFactory("user.odb");
    em = emf.createEntityManager();


    final JTextField txtUsername = new JTextField();
    txtUsername.setFont(new Font("Segoe UI Light", Font.PLAIN, 30));
    txtUsername.setHorizontalAlignment(SwingConstants.CENTER);
    txtUsername.setToolTipText("username");
    txtUsername.setText("");
    txtUsername.setBounds(220, 30, 177, 52);
    contentPane.add(txtUsername);
    txtUsername.setColumns(10);

    final JPasswordField passwordField = new JPasswordField();
    passwordField.setFont(new Font("Tahoma", Font.PLAIN, 30));
    passwordField.setHorizontalAlignment(SwingConstants.CENTER);
    passwordField.setBounds(220, 93, 177, 52);
    contentPane.add(passwordField);

    JButton btnNewUser = new JButton("New user");
    btnNewUser.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            username = txtUsername.getText();
            password = passwordField.getPassword();

            System.out.println(username);
            TypedQuery<Long> q = em.createQuery(
                    "SELECT COUNT(u) FROM User u "
                    + "WHERE u.name = '" + username + "'", Long.class);

            if (q.getSingleResult()>0) {
                JOptionPane.showMessageDialog(contentPane.getParent(), "A user with this name already exists.");
            } else {
                em.getTransaction().begin();
                User newUser = new User(username, password.toString());
                em.persist(newUser);
                em.getTransaction().commit();
                JOptionPane.showMessageDialog(contentPane.getParent(), "User created.");
            }   
        }
    });
    btnNewUser.setFont(new Font("Segoe WP Semibold", Font.PLAIN, 25));
    btnNewUser.setBackground(Color.WHITE);
    btnNewUser.setBounds(71, 175, 149, 63);
    contentPane.add(btnNewUser);

}
}

and the error:

Exception in thread "AWT-EventQueue-0" [ObjectDB 2.5.3_03] SELECT COUNT(u) FROM  ==> User <==  u WHERE u.name = ''
javax.persistence.PersistenceException
Type User is not found (error 301)
 (position 21)  at com.objectdb.jpa.JpaQuery.getSingleResult(JpaQuery.java:723)
    at sg.FrameLogIn$2.actionPerformed(FrameLogIn.java:113)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: com.objectdb.o.TEX: Type User is not found
    at com.objectdb.o.MSG.e(MSG.java:107)
    at com.objectdb.o.TRS.g(TRS.java:212)
    at com.objectdb.o.SYR.q(SYR.java:259)
    at com.objectdb.o.SYR.n(SYR.java:188)
    at com.objectdb.o.QRC.<init>(QRC.java:152)
    at com.objectdb.o.QRM.U6(QRM.java:250)
    at com.objectdb.o.MST.U6(MST.java:933)
    at com.objectdb.o.WRA.U6(WRA.java:293)
    at com.objectdb.o.WSM.U6(WSM.java:114)
    at com.objectdb.o.QRR.g(QRR.java:245)
    at com.objectdb.o.QRR.f(QRR.java:154)
    at com.objectdb.jpa.JpaQuery.getSingleResult(JpaQuery.java:716)
    ... 37 more

Thanks, also for the record i will not be storing plaintext passwords, I'm just trying to get a basic DB working before I start implementing hashed passwords.

dahui
  • 1,978
  • 2
  • 15
  • 35
  • Do you have a JPA Entity defined for User object? – Mubin Dec 23 '13 at 22:57
  • Yeah the class has all the @Entity stuff etc. Searching the database works once I add a single entity and I can view the DB with a bunch of records in, so that all works – dahui Dec 23 '13 at 23:28

1 Answers1

3

This could happen if the entity class is not in the database yet (no instances of that class have been persisted yet), and a persistence unit is not defined.

If this seems to be the cause, either define a persistence unit or introduce the class to ObjectDB before the query, for example by:

  em.getMetamodel().entity(User.class);
ObjectDB
  • 1,294
  • 7
  • 8