Hibernate - 如何检查用户是否存在?

时间:2016-02-10 02:10:34

标签: java hibernate

我遇到了奇怪的问题,我试图在JavaFX应用程序中使用Hibernate,我希望Hibernate将检查数据库中是否存在输入的值,但是...当我输入这些值时,Hibernate会删除所有我的USER表中的记录而不是检查输入的值是否存在...为什么?这是一个代码:

EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("clinic");
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    User user = new User();

    user.setUsername(loginField.getText());
    user.setPassword(passwordField.getText());


    Query query = entityManager.createQuery("FROM User WHERE username= :username AND password= :password", User.class);
    query.setParameter("username", user.getUsername());
    query.setParameter("password", user.getPassword());

    String result = query.getResultList().toString();

    System.out.println(result);

    // if user exist then main window will appear:
  //root = FXMLLoader.load(getClass().getResource("/view/Main.fxml"));
    //stage = (Stage) logInButton.getScene().getWindow();
    //stage.setTitle("Przychodnia");
    //stage.setScene(new Scene(root, 750, 530));
    //stage.show();
    //return;


    entityManager.close();
    entityManagerFactory.close();

的persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence  http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="clinic" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
        <property name="javax.persistence.jdbc.user" value="root" />
        <property name="javax.persistence.jdbc.password" value="root" />
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3307/przychodniadb" />
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
        <property name="hibernate.hbm2ddl.auto" value="create"/>
    </properties>
</persistence-unit>

1 个答案:

答案 0 :(得分:2)

摆脱<property name="hibernate.hbm2ddl.auto" value="create"/>因为它会在每次启动时重新创建数据库