在实体bean中插入时不会自动设置@Id

时间:2013-05-23 17:58:40

标签: java mysql hibernate jboss ejb

我有一个相当简单的EJB应用程序,它由

组成

一个实体Bean:

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Employee implements Serializable {

private static final long serialVersionUID = -8450766960140252704L;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="employee_number", nullable=false)
private int employeeNumber;
private String firstname;
private String inital;
private String lastname;
private int age;
private Date birthday;
private String street;
@Column(name="house_number")
private String houseNumber;
private String postalcode;
private String city;
private String department;
@Column(name="sallery_group")
private String salleryGroup;

public int getEmployeeNumber() {
    return employeeNumber;
}
public void setEmployeeNumber(int employeeNumber) {
    this.employeeNumber = employeeNumber;
}
public String getFirstname() {
    return firstname;
}
public void setFirstname(String firstname) {
    this.firstname = firstname;
}
public String getInital() {
    return inital;
}
public void setInital(String inital) {
    this.inital = inital;
}
public String getLastname() {
    return lastname;
}
public void setLastname(String lastname) {
    this.lastname = lastname;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
public Date getBirthday() {
    return birthday;
}
public void setBirthday(Date birthday) {
    this.birthday = birthday;
}
public String getStreet() {
    return street;
}
public void setStreet(String street) {
    this.street = street;
}
public String getHouseNumber() {
    return houseNumber;
}
public void setHouseNumber(String houseNumber) {
    this.houseNumber = houseNumber;
}
public String getPostalcode() {
    return postalcode;
}
public void setPostalcode(String postalcode) {
    this.postalcode = postalcode;
}
public String getCity() {
    return city;
}
public void setCity(String city) {
    this.city = city;
}
public String getDepartment() {
    return department;
}
public void setDepartment(String department) {
    this.department = department;
}
public String getSalleryGroup() {
    return salleryGroup;
}
public void setSalleryGroup(String salleryGroup) {
    this.salleryGroup = salleryGroup;
}

@Override
public String toString() {

    StringBuffer sb = new StringBuffer();

    sb.append("Employee Number: " + this.getEmployeeNumber() + "\n");
    sb.append("Firstname: " + this.getFirstname() + "\n");
    sb.append("Inital: " + this.getInital() + "\n");
    sb.append("Lastname: " + this.getLastname() + "\n");
    sb.append("Age: " + this.getAge() + "\n");
    sb.append("Birthday: " + this.getBirthday() + "\n");
    sb.append("Street: " + this.getStreet() + "\n");
    sb.append("House Number: " + this.getHouseNumber() + "\n");
    sb.append("Postalcode: " + this.getPostalcode() + "\n");
    sb.append("City: " + this.getCity() + "\n");
    sb.append("Department: " + this.getDepartment() + "\n");
    sb.append("Sallery Group: " + this.getSalleryGroup() + "\n");

    return sb.toString();
}

@Override
public boolean equals(Object obj) {

    if(obj == null || this.getClass() != obj.getClass())
    {
        return false;
    }
    else if (obj == this)
    {
        return true;
    }
    else
    {
        Employee employee = (Employee)obj;
        return (
               ((this.getFirstname() == null && employee.getFirstname() == null) || (this.getFirstname().equals(employee.getFirstname()))) &&
               ((this.getInital() == null && employee.getInital() == null) || (this.getInital().equals(employee.getInital()))) &&
               ((this.getLastname() == null && employee.getLastname() == null) || (this.getLastname().equals(employee.getLastname()))) &&
               this.getAge() == employee.getAge() &&
               ((this.getBirthday() == null && employee.getBirthday() == null) || (this.getBirthday().equals(employee.getBirthday()))) &&
               ((this.getStreet() == null && employee.getStreet() == null) || (this.getStreet().equals(employee.getStreet()))) &&
               ((this.getHouseNumber() == null && employee.getHouseNumber() == null) || (this.getHouseNumber().equals(employee.getHouseNumber()))) &&
               ((this.getPostalcode() == null && employee.getPostalcode() == null) || (this.getPostalcode().equals(employee.getPostalcode()))) &&
               ((this.getCity() == null && employee.getCity() == null) || (this.getCity().equals(employee.getCity()))) &&
               ((this.getDepartment() == null && employee.getDepartment() == null) || (this.getDepartment().equals(employee.getDepartment()))) &&
               ((this.getSalleryGroup() == null && employee.getSalleryGroup() == null) || (this.getSalleryGroup().equals(employee.getSalleryGroup()))));

    }
}

}

一个会话Bean

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

@Stateless
public class EmployeeManagementBean implements EmployeeManagement {

@PersistenceContext(unitName="EmployeePersistenceUnit")
private EntityManager entityManager;

@Override
public Employee create() {
    return new Employee();  
}

@Override
public void store(Employee employee) {
    entityManager.persist(employee);
}

@Override
public Employee findEmployeeWithNumber(int employeeNumber) {
    return entityManager.find(Employee.class, employeeNumber);
}

}

在我的客户端中,我只是在会话bean上调用create(),将所有属性设置为除了我的案例employeeNumber之外的id字段。然后我调用store()并将对象传递给会话bean。然后将对象正确地存储在数据库中,主键由mysql数据库自动生成。

问题

我的问题是,生成的id不会传回给对象。因此,在调用store()并因此调用entityManager.persist()之后,getEmployeeNumber()的调用总是返回0.根据我在Web上阅读的许多内容,@ Id字段应该由数据库生成的id自动填充。希望有人可以帮助我。 entityManager.flush()无法解决问题。

更多详情

我正在使用JBoss 7.1.0和MySQL 5.6。 MySQL JDBC驱动程序放在部署文件夹中。

的persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 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">

<persistence-unit name="EmployeePersistenceUnit" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>java:jboss/datasources/MySQLEmployeeManagementDS</jta-data-source>
</persistence-unit>

standalone.xml

<datasource jndi-name="java:jboss/datasources/MySQLEmployeeManagementDS" pool-name="MySQLEmployeeManagementDS" enabled="true" jta="true" use-java-context="true" use-ccm="true">
                <connection-url>
                    jdbc:mysql://localhost:3306/employee_management
                </connection-url>
                <driver>
                    mysql-connector-java-5.1.25.jar
                </driver>
                <pool>
                    <min-pool-size>
                        10
                    </min-pool-size>
                    <max-pool-size>
                        100
                    </max-pool-size>
                    <prefill>
                        true
                    </prefill>
                    <use-strict-min>
                        false
                    </use-strict-min>
                    <flush-strategy>
                        FailingConnectionOnly
                    </flush-strategy>
                </pool>
                <security>
                    <user-name>
                        root
                    </user-name>
                    <password>
                        test
                    </password>
                </security>
            </datasource>
            <drivers>
                <driver name="mysql-connector-java-5.1.25.jar" module="com.mysql">
                    <xa-datasource-class>
                        com.mysql.jdbc.jdbc2.optional.MysqlXADataSource
                    </xa-datasource-class>
                </driver>
            </drivers>

表格

CREATE TABLE `employee` (
`employee_number` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL,
`inital` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL,
`lastname` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`birthday` datetime DEFAULT NULL,
`street` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL,
`house_number` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL,
`postalcode` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL,
`city` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL,
`department` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL,
`sallery_group` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`employee_number`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

1 个答案:

答案 0 :(得分:1)

我相信你观察到的行为是正确的。使用GenerationType.IDENTITY或GenerationType.SEQUENCE策略时,在插入行之前不知道id值。

如果在持久化实体后立即需要该值,则必须调用EntityManager.flush()以强制与数据库同步,然后检索对象 - 此时将设置id。

您也可以尝试使用HQL查询,而不是查找方法

Query q = em.createQuery("select e from Employee where e.id = :id");
q.setId(employeeNumber);
return q.getSingleResult()

如果将EJB与远程接口一起使用,则可能会出现另一个问题。假设以下流程

  1. 在客户端调用EmployeeManagementBean.create(),然后在客户端获取Employee对象,我们称之为e1。

  2. 在客户端,您调用EmployeeManagementBean.store(e1)

  3. 在客户端,您调用e1.getEmployeeNumber()并获得0

  4. 问题如下。当您调用EmployeeManagementBean.store(e1)时,e1对象的副本将传递给EJB方法,该对象在服务器端进行修改,但客户端上的原始对象不会。这是因为在远程EJB调用期间,参数作为原始对象的序列化副本传递给服务器。

    在客户端没有看到服务器端的远程更改(例如更改id)。

    为了克服这个问题,您可以按如下方式更改存储方法:

    public Employee store(Employee employee) {
        entityManager.persist(employee);
        entityManager.flush();
        return employee; //employee should have id set to the DB value
    }