一:
@Entity
@Table(name="Identity")
public class Identity implements Serializable {
@Id
@GeneratedValue(generator="test")
@GenericGenerator(name="test", strategy="foreign", parameters=@Parameter(name="property", value="person"))
private int id;
private int number;
@OneToOne(mappedBy="identity")
private Person person;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
@Entity
@Table(name="person")
public class Person implements Serializable{
@Id
@GeneratedValue
private int pid;
private String name;
@OneToOne(cascade=CascadeType.ALL)
@PrimaryKeyJoinColumn
private Identity identity;
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public Identity getIdentity() {
return identity;
}
public void setIdentity(Identity identity) {
this.identity = identity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Stateless
@Remote
public class PersonManagerBean implements PersonManager {
@PersistenceContext(unitName="jpa_04_one2onePU")
public EntityManager em;
public void addIdentity(Identity identity) {
em.persist(identity);
}
public void addPerson(Person person) {
em.persist(person);
}
public Person getPersonById(int id) {
return em.find(Person.class, id);
}
}
client端:
public class One2One_client {
public static void main(String[] args) {
try {
Context context = new InitialContext();
PersonManager pm = (PersonManager)context.lookup("PersonManagerBean/remote");
Identity ide = new Identity();
// ide.setId(1);
ide.setNumber(12345);
// pm.addIdentity(ide);
Person person = new Person();
person.setName("xxx");
person.setIdentity(ide);
pm.addPerson(person);
// Person person1 = pm.getPersonById(0);
// System.out.println(person1.getName());
// Identity identity = person1.getIdentity();
// System.out.println(identity.getNumber());
} catch (NamingException e) {
e.printStackTrace();
}
}
}
访问时跑出异常:
Exception in thread "main" java.lang.reflect.UndeclaredThrowableException
at $Proxy2.addPerson(Unknown Source)
at com.luc.ejb.One2One_client.main(One2One_client.java:23)
Caused by: java.lang.ClassNotFoundException: org.hibernate.id.IdentifierGenerationException