使用ObjectDB搜索空用户数据库时出现问题 [英] Problems searching empty user database with ObjectDB

查看:180
本文介绍了使用ObjectDB搜索空用户数据库时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个使用ObjectDB创建和维护一组数据库的java应用程序。我目前正在尝试实现一个DB来存储由用户名和密码字符串组成的用户对象。在JFrame / swing类上,我有一个用于创建新用户的按钮,当点击此按钮时,我想要发生以下事件:


  1. 创建(或连接到)数据库

  2. 搜索数据库以查看是否存在具有提供的用户名的用户对象

  3. 如果用户已存在, ,否则创建用户

但是,当点击这个按钮时,我得到一个User not found查询对象的结果。我相信它是因为我有一个空数据库,但我想让代码第一次运行程序,因此它需要处理一个空数据库。我试图更改代码,以在首次运行查询之前创建一个新用户,然后该代码如何在每次点击按钮时都能工作,并且它可以检测是否需要创建新用户。



我试图创建一个默认或管理类型的用户,所以搜索会工作,但这意味着每次重复默认程序运行,这显然是一个不需要的功能,我不能做查询检查数据库是否为空(所以我只能创建默认用户在程序的第一次运行),因为这是问题我



所以,对于有ObjectDB经验的人,有没有办法处理空数据库搜索的情况?



这是代码的相关部分:

  public class FrameLogIn extends JFrame {

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

/ **
*启动应用程序。
* /
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 $ b}
}
});
}

/ **
*创建框架。
* /
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.setHorizo​​ntalAlignment(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.setHorizo​​ntalAlignment(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(),具有此名称的用户已存在。);
} else {
em.getTransaction()。begin();
用户newUser = new User username,password.toString());
em.persist(newUser);
em.getTransaction()。commit();
JOptionPane.showMessageDialog(contentPane.getParent created。);
}
}
});
btnNewUser.setFont(new Font(Segoe WP Semibold,Font.PLAIN,25));
btnNewUser.setBackground(Color.WHITE);
btnNewUser.setBounds(71,175,149,63);
contentPane.add(btnNewUser);

}
}

>

 线程AWT-EventQueue-0中的异常[ObjectDB 2.5.3_03] SELECT COUNT(u)FROM ==> User< == u WHERE u.name =''
javax.persistence.PersistenceException
在com.objectdb.jpa找不到类型用户(错误301)
(位置21)。 JpaQuery.getSingleResult(JpaQuery.java:723)
at sg.FrameLogIn $ 2.actionPerformed(FrameLogIn.java:113)
at javax.swing.AbstractButton.fireActionPerformed(未知来源)
at javax .swing.AbstractButton $ Handler.actionPerformed(未知源)
at javax.swing.DefaultButtonModel.fireActionPerformed(未知源)
at javax.swing.DefaultButtonModel.setPressed(未知源)
at javax .swing.plaf.basic.BasicButtonListener.mouseReleased(未知源)
at java.awt.Component.processMouseEvent(未知源)
at javax.swing.JComponent.processMouseEvent(未知源)
在java.awt.Component.processEvent(未知源)
在java.awt.Container.processEvent(未知源)
在java.awt.Component.dispatchEventImpl(未知源)
在java .awt.Container.dispatchEventImpl(未知源)
at java.awt.Component.dispatchEvent(未知源)
at java.awt.LightweightDispatcher.retargetMouseEvent(未知源)
at java.awt .LightweightDispatcher.processMouseEvent(未知源)
at java.awt.LightweightDispatcher.dispatchEvent(未知源)
at java.awt.Container.dispatchEventImpl(未知源)
at java.awt.Window .dispatchEventImpl(未知源)
at java.awt.Component.dispatchEvent(未知源)
at java.awt.EventQueue.dispatchEventImpl(未知源)
at java.awt.EventQueue.access $ 200(未知源)
在java.awt.EventQueue $ 3.run(未知源)
在java.awt.EventQueue $ 3.run(未知源)
在java.security.AccessController。 doPrivileged(native方法)
at java.security.ProtectionDomain $ 1.doIntersectionPrivilege(未知源)
at java.security.ProtectionDomain $ 1.doIntersectionPrivilege(未知源)
at java.awt.EventQueue $ 4 .run(Unknown Source)
at java.awt.EventQueue $ 4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native方法)
at java.security.ProtectionDomain $ 1 。未知来源)
at java.awt.EventQueue.dispatchEvent(未知源)
at java.awt.EventDispatchThread.pumpOneEventForFilters(未知源)
at java.awt.EventDispatchThread.pumpEventsForFilter (未知源)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(未知源)
at java.awt.EventDispatchThread.pumpEvents(未知源)
at java.awt.EventDispatchThread.pumpEvents源)
在java.awt.EventDispatchThread.run(未知源)
导致:com.objectdb.o.TEX:类型未找到用户
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)
...谢谢,也为了记录我不会存储明文密码,我只是试图

解决方案

如果实体类不在数据库中,可能会发生这种情况



如果这似乎是原因,可以定义一个持久化单元或在查询之前将类引入ObjectDB,例如:

  em.getMetamodel()。entity(User.class); 


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.

解决方案

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搜索空用户数据库时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆