Wildfly 8.2 - Hibernate JTA Remove 失败并删除分离的实例(已合并)

Wildfly 8.2 - Hibernate JTA Remove fails with Removing a detached instance (allready merged)

我是 hibernate 的新手,我已经使用 persistence.xml 和自动生成的实体和 DAO 类.

构建了一个项目

在我的测试中,持久化和合并有效,但删除无效,它失败并出现以下错误:

    java.lang.IllegalArgumentException: Removing a detached instance packagename.dto.Clientinformation#test1

我搜索了一下,认为问题出在删除时对象没有合并,所以我在删除之前添加了合并,但问题仍然存在。

我想我的持久性设置可能有问题。

这是 persistence.xml 文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="2.1" 
 xmlns="http://xmlns.jcp.org/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/persistence_2_1.xsd">

<persistence-unit name="datageneralpersistenceunit">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

    <class>packagename.dto.Clientinformation</class>


    <properties>

        <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform"/>

        <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
        <property name="hibernate.connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider" />
        <property name="hibernate.connection.url" value="jdbc:postgresql://host:port/Database" />
        <property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
        <property name="hibernate.connection.username" value="username"/>
        <property name="hibernate.connection.password" value="password"/>
        <property name="hibernate.default_schema" value="general"/>


        <property name="jboss.entity.manager.jndi.name" value="java:app/GeneralDatabaseEntityManager"/>

        <!-- value="create" to build a new database on each run; value="update" to modify an existing database; value="create-drop" means the same as "create" but also drops tables when Hibernate closes; value="validate" makes no changes to the database -->
        <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
        <property name="hibernate.connection.charSet" value="UTF-8"/>
        <!-- Uncomment the following two properties for JBoss only -->
        <property name="hibernate.validator.apply_to_ddl" value="false" />
        <property name="hibernate.validator.autoregister_listeners" value="false" />        
        <property name="hibernate.connection.autocommit" value="true"/> 
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.use_sql_comments" value="true" />
        <property name="hibernate.format_sql" value="true" />


        <property name="hibernate.c3p0.acquire_increment" value="1" />
        <property name="hibernate.c3p0.idle_test_period" value="60" />
        <property name="hibernate.c3p0.min_size" value="1" />
        <property name="hibernate.c3p0.max_size" value="2" />
        <property name="hibernate.c3p0.max_statements" value="50" />
        <property name="hibernate.c3p0.timeout" value="30000" />
        <property name="hibernate.c3p0.acquireRetryAttempts" value="1" />
        <property name="hibernate.c3p0.acquireRetryDelay" value="250" />


        <property name="hibernate.current_session_context_class" value="thread" />  
    </properties>

</persistence-unit>
    </persistence>

实体;

    import java.util.Date;
    import java.util.HashSet;
    import java.util.Set;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.Id;
    import javax.persistence.OneToMany;
    import javax.persistence.Table;
    import javax.persistence.Temporal;
    import javax.persistence.TemporalType;

    /**
     * Clientinformation generated by hbm2java
     */
    @Entity
    @Table(name = "clientinformation")
    public class Clientinformation implements java.io.Serializable {

        private String responsibleusernameid;
        private String country;
        private String firstname;
        private String middlename;
        private String lastname;
        private String telephone;
        private String address;
        private String email;
        private String company;
        private String department;
        private String description;
        private Date creationdate;
        private String password;
        private Short discount;
        private Set<Tenants> tenantses = new HashSet<Tenants>(0);
        private Set<Payments> paymentses = new HashSet<Payments>(0);

        public Clientinformation() {
        }

        public Clientinformation(String responsibleusernameid, String country,
                String firstname, String lastname, String telephone,
                String address, String email, Date creationdate, String password) {
            this.responsibleusernameid = responsibleusernameid;
            this.country = country;
            this.firstname = firstname;
            this.lastname = lastname;
            this.telephone = telephone;
            this.address = address;
            this.email = email;
            this.creationdate = creationdate;
            this.password = password;
        }

        public Clientinformation(String responsibleusernameid, String country,
                String firstname, String middlename, String lastname,
                String telephone, String address, String email, String company,
                String department, String description, Date creationdate,
                String password, Short discount, Set<Tenants> tenantses,
                Set<Payments> paymentses) {
            this.responsibleusernameid = responsibleusernameid;
            this.country = country;
            this.firstname = firstname;
            this.middlename = middlename;
            this.lastname = lastname;
            this.telephone = telephone;
            this.address = address;
            this.email = email;
            this.company = company;
            this.department = department;
            this.description = description;
            this.creationdate = creationdate;
            this.password = password;
            this.discount = discount;
            this.tenantses = tenantses;
            this.paymentses = paymentses;
        }

        @Id
        @Column(name = "responsibleusernameid", unique = true, nullable = false, length = 50)
        public String getResponsibleusernameid() {
            return this.responsibleusernameid;
        }

        public void setResponsibleusernameid(String responsibleusernameid) {
            this.responsibleusernameid = responsibleusernameid;
        }

        @Column(name = "country", nullable = false, length = 100)
        public String getCountry() {
            return this.country;
        }

DAO:

    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;

    import packagename.dto.Clientinformation;

    /**
     * Home object for domain model class Clientinformation.
     * @see packagename.dto.Clientinformation
     * @author Hibernate Tools
     */
    @Stateless
    public class ClientinformationHome {

        private static final Log log = LogFactory
                .getLog(ClientinformationHome.class);

        @PersistenceContext
        private EntityManager entityManager;

        public void persist(Clientinformation transientInstance) {
            log.debug("persisting Clientinformation instance");
            try {
                entityManager.persist(transientInstance);

                log.debug("persist successful");
            } catch (RuntimeException re) {
                log.error("persist failed", re);
                throw re;
            }
        }

        public void remove(Clientinformation persistentInstance) {
            log.debug("removing Clientinformation instance");
            try {
                entityManager.remove(persistentInstance);
                log.debug("remove successful");
            } catch (RuntimeException re) {
                log.error("remove failed", re);
                throw re;
            }
        }

        public Clientinformation merge(Clientinformation detachedInstance) {
            log.debug("merging Clientinformation instance");
            try {
                Clientinformation result = entityManager.merge(detachedInstance);
                log.debug("merge successful");
                return result;
            } catch (RuntimeException re) {
                log.error("merge failed", re);
                throw re;
            }
        }

        public Clientinformation findById(String id) {
            log.debug("getting Clientinformation instance with id: " + id);
            try {
                Clientinformation instance = entityManager.find(
                        Clientinformation.class, id);
                log.debug("get successful");
                return instance;
            } catch (RuntimeException re) {
                log.error("get failed", re);
                throw re;
            }
        }
    }

失败的测试:

    public void test() {


            try {

                Context ctx = new InitialContext();
                ClientinformationHome clientinformationHome = (ClientinformationHome) ctx.lookup("java:app/app-name/ClientinformationHome");

                Date now = new Date();



                log.debug("inserting new record");
                // Insert new record
                Clientinformation user1 = new Clientinformation();
                try {
                    user1.setResponsibleusernameid("test1");
                    user1.setFirstname("fnamr");
                    user1.setMiddlename("sname");
                    user1.setLastname("lname");
                    user1.setTelephone("+1111111111");
                    user1.setCountry("Spain");
                    user1.setAddress("Arven 2372 1, Madrid, spain");
                    user1.setEmail("test1@gt.com");
                    user1.setCompany("the company");
                    user1.setDepartment("Information Technologies");
                    user1.setDescription("This is de test user");
                    user1.setCreationdate(now);
                    user1.setPassword("test1111dd");
                    user1.setDiscount((short) 0);
                    clientinformationHome.persist(user1);
                } catch (Exception e) {
                    log.debug(e.getMessage());
                }


                log.debug("updating existing record");
                // Update existing record
                try {
                    log.debug("Get existing record");
                    Clientinformation user2 = clientinformationHome
                            .findById("test1");
                    log.debug("Setting middlename");
                    user2.setMiddlename("sname2");
                    clientinformationHome.merge(user2);

                    log.debug("Updated Client information");
                } catch (Exception e) {
                    log.debug(e.getMessage());
                }



                log.debug("remove existing record");
                // remove existing record
                try {

                    log.debug("Searching client information to remove");
                    Clientinformation user5 = clientinformationHome
                            .findById("test1");
                    log.debug("Found client information to remove");
                    if (null != user5) {
                        log.debug("Removing client information with name " + user5.getFirstname());
                        user5 = clientinformationHome.merge(user5);
                        log.debug("Client information merged");                 
                        clientinformationHome.remove(user5);
                        log.debug("Client information removed");
                    } else {
                        log.debug("No records found");
                    }
                } catch (Exception e) {
                    log.debug(e.getMessage());
                }
            } catch (Exception e) {

                log.debug(e.getMessage());
            } finally {

            }


        }

有人可以帮助我吗?谢谢!

好的,明白了,它在我的测试中缺少@Stateless 注释class...成功了,无论如何谢谢