Hibernate重复enrty插入

时间:2017-03-14 23:04:05

标签: java hibernate websocket java-ee-6 wildfly-8

我在Wildfly服务器中部署的JavaEE应用程序中使用Hibernate和websockets。 我的问题是,当我尝试插入新用户时,hibernate复制插入,我得到2个用户使用不同的id,因为我使用自动生成主键。 我尝试了太多的解决方案,但没有一个帮助:(  这是我的例子:

用户表

package database;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;
import org.hibernate.id.IncrementGenerator;

import javax.persistence.*;
import java.io.Serializable;

import javax.persistence.*;


@Entity

@Table(name = "Eutilisateur")
public class Eutilisateur implements Serializable{
    private int idUser;
    private String username;
    private String password;
    private String typeUser;

    @Id
   @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "id_user", nullable = false,updatable = false)
    public int getIdUser() {
        return idUser;
    }

    public void setIdUser(int idUser) {
        this.idUser = idUser;
    }

    @Basic
    @Column(name = "username", nullable = false, length = 20)
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Basic
    @Column(name = "password", nullable = false, length = 20)
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Basic
    @Column(name = "type_user", nullable = false, length = 20)
    public String getTypeUser() {
        return typeUser;
    }

    public void setTypeUser(String typeUser) {
        this.typeUser = typeUser;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Eutilisateur that = (Eutilisateur) o;

        if (idUser != that.idUser) return false;
        if (username != null ? !username.equals(that.username) : that.username != null) return false;
        if (password != null ? !password.equals(that.password) : that.password != null) return false;
        if (typeUser != null ? !typeUser.equals(that.typeUser) : that.typeUser != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = idUser;
        result = 31 * result + (username != null ? username.hashCode() : 0);
        result = 31 * result + (password != null ? password.hashCode() : 0);
        result = 31 * result + (typeUser != null ? typeUser.hashCode() : 0);
        return result;
    }
}

webSocket类

import com.sun.org.apache.regexp.internal.RE;
import service.WebHeler;


import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.BufferedReader;
import java.io.IOException;


@ServerEndpoint(value = "/DynamicWeb")
public class DynamicWeb {
    @OnOpen
    public void onOpen(Session session)  {
        System.out.println(session.getId() + " has opened a connection");

    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("Message from " + session.getId() + ": " + message);

Response.getResponse(message,getClass().getClassLoader());
        session.getBasicRemote().sendText(" message  recieved");
       try {



         String resopnse = Response.getResponse(message,getClass().getClassLoader());
            session.getBasicRemote().sendText(resopnse);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session){

        System.out.println("Session " +session.getId()+" has ended");
    }
}

Response类

 public static String getResponse(String messsage, ClassLoader loader) {
        String file = "";
        if (messsage.startsWith("command")) {
            return databaseCommand(messsage);
        }

        String full = "";

        try {
            InputStream inputStream = loader
                    .getResourceAsStream(file);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String chunk = "";
            while ((chunk = reader.readLine()) != null) {
                full += chunk + " ";
            }
            System.out.println(full);

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

        return full;
    }

    public static String databaseCommand(String message) {
        String[] parametrs = message.split(";");
        String response = "";
        if (parametrs[1].equals("adduser")) {
            String userName = parametrs[2];
            String Password = parametrs[3];
            String Type = parametrs[4];
            if (userName.equals(""))
                return "user name length ==0";

            System.out.println("add user command " + userName + "  " + Password + " " + Type);

           Session session = HibernateHelper.getSession();
        Transaction transaction = session.getTransaction();
        transaction.begin();
        try{
            Eutilisateur user = new Eutilisateur();
            user.setPassword(pass);
            user.setTypeUser(type);
            user.setUsername(username);
            session.save(user);

        }catch (HibernateException e){
            e.printStackTrace();
            transaction.rollback();
        }finally {
            transaction.commit();

        }
    }

        return response;
    }

}

我的hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <!-- database related configurations -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/pro</property>
      <property name="connection.username">****</property>
      <property name="connection.password">****</property>
    <!--<property name="hibernate.hbm2ddl.auto">validate</property>-->
    <property name="pool_size">5</property>
    <property name="connection.autocommit">true</property>
    <property name="show_sql">true</property>
    <property name="dialect">
      org.hibernate.dialect.MySQL5Dialect</property>
    <mapping class="database.Eutilisateur"/>
  </session-factory>
</hibernate-configuration>

日志错误是这样的:我认为我有多线程runnig那里,我不能停止'em

23:30:56,064 INFO  [org.hibernate.cfg.annotations.Version] (default task-31) Hibernate Annotations 3.4.0.GA
23:30:56,080 INFO  [org.hibernate.cfg.Environment] (default task-31) Hibernate 3.3.0.SP1
23:30:56,080 INFO  [org.hibernate.cfg.Environment] (default task-31) hibernate.properties not found
23:30:56,080 INFO  [org.hibernate.cfg.Environment] (default task-31) Bytecode provider name : javassist
23:30:56,080 INFO  [org.hibernate.cfg.Environment] (default task-31) using JDK 1.4 java.sql.Timestamp handling
23:30:56,111 INFO  [org.hibernate.annotations.common.Version] (default task-31) Hibernate Commons Annotations 3.1.0.GA
23:30:56,111 INFO  [org.hibernate.cfg.Configuration] (default task-31) configuring from resource: /Hibernate.cfg.xml
23:30:56,111 INFO  [org.hibernate.cfg.Configuration] (default task-31) Configuration resource: /Hibernate.cfg.xml
23:30:56,158 INFO  [org.hibernate.cfg.Configuration] (default task-31) Configured SessionFactory: null
23:30:56,158 INFO  [org.hibernate.cfg.search.HibernateSearchEventListenerRegister] (default task-31) Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
23:30:56,173 INFO  [org.hibernate.cfg.AnnotationBinder] (default task-31) Binding entity from annotated class: database.Eutilisateur
23:30:56,189 INFO  [org.hibernate.cfg.annotations.EntityBinder] (default task-31) Bind entity database.Eutilisateur on table Eutilisateur
23:30:56,204 INFO  [org.hibernate.cfg.AnnotationBinder] (default task-31) 
(default task-31) Using Hibernate built-in connection pool (not for production use!)
23:30:56,267 INFO  [org.hibernate.connection.DriverManagerConnectionProvider] (default task-31) Hibernate connection pool size: 20
23:30:56,267 INFO  [org.hibernate.connection.DriverManagerConnectionProvider] (default task-31) autocommit mode: true
23:30:56,267 INFO  [org.hibernate.connection.DriverManagerConnectionProvider] (default task-31) using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/pro
23:30:56,267 INFO  [org.hibernate.connection.DriverManagerConnectionProvider] (default task-31) connection properties: {user=root, password=****, autocommit=true}
23:30:56,486 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) RDBMS: MySQL, version: 5.7.13-log
23:30:56,486 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.9 ( Revision: ${svn.Revision} )
23:30:56,486 INFO  [org.hibernate.dialect.Dialect] (default task-31) Using dialect: org.hibernate.dialect.MySQL5Dialect
23:30:56,486 INFO  [org.hibernate.transaction.TransactionFactoryFactory] (default task-31) Using default transaction strategy (direct JDBC transactions)
23:30:56,486 INFO  [org.hibernate.transaction.TransactionManagerLookupFactory] (default task-31) No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
23:30:56,486 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Automatic flush during beforeCompletion(): disabled
23:30:56,486 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Automatic session close at end of transaction: disabled
23:30:56,486 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) JDBC batch size: 15
23:30:56,486 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) JDBC batch updates for versioned data: disabled
23:30:56,486 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Scrollable result sets: enabled
23:30:56,486 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) JDBC3 getGeneratedKeys(): enabled
23:30:56,486 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Connection release mode: auto
23:30:56,486 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Maximum outer join fetch depth: 2
23:30:56,486 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Default batch fetch size: 1
23:30:56,486 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Generate SQL with comments: disabled
23:30:56,486 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Order SQL updates by primary key: disabled
23:30:56,501 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Order SQL inserts for batching: disabled
23:30:56,501 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
23:30:56,501 INFO  [org.hibernate.hql.ast.ASTQueryTranslatorFactory] (default task-31) Using ASTQueryTranslatorFactory
23:30:56,501 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Query language substitutions: {}
23:30:56,501 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) JPA-QL strict compliance: disabled
23:30:56,501 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Second-level cache: enabled
23:30:56,501 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Query cache: disabled
23:30:56,501 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
23:30:56,501 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Optimize cache for minimal puts: disabled
23:30:56,501 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Structured second-level cache entries: disabled
23:30:56,501 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Echoing all SQL to stdout
23:30:56,501 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Statistics: disabled
23:30:56,501 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Deleted entity synthetic identifier rollback: disabled
23:30:56,501 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Default entity-mode: pojo
23:30:56,501 INFO  [org.hibernate.cfg.SettingsFactory] (default task-31) Named query checking : enabled
23:30:56,517 INFO  [org.hibernate.impl.SessionFactoryImpl] (default task-31) building session factory
23:30:56,658 INFO  [org.hibernate.impl.SessionFactoryObjectFactory] (default task-31) Not binding factory to JNDI, no JNDI name configured
23:30:56,689 INFO  [stdout] (default task-31) Hibernate: insert into Eutilisateur (password, type_user, username) values (?, ?, ?)
23:30:56,751 INFO  [stdout] (default task-31) add user command te  best fddf

23:30:56,751 INFO  [stdout] (default task-31) Hibernate: insert into Eutilisateur (password, type_user, username) values (?, ?, ?)
23:30:56,783 ERROR [stderr] (default task-31) java.io.IOException: UT002002: Channel is closed

0 个答案:

没有答案