因为,我正在阅读JPA(Java Persistence API)。我在那里读到了Embeddable Classes。所以,我试图在我的实体类中使用该概念。但在使用这个时,我面临着一个分离实体的问题。
这里我在Entity中有Embeddable Class(ZipCode)。
可嵌入班级
@Embeddable public class ZipCode {
private String zip;
private String plusFour;
//getter & setter also.
}
实体类
@Entity
@Table(name = "address")
public class Address {
@Id
@GeneratedValue(strategy = IDENTITY)
private long id;
@Embedded
private ZipCode zipCode;
//getter & setter also.
}
我的持久性代码:
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Inject
private CrudService crudService;
public RegisterServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ZipCode z = new ZipCode();
z.setZip("bharti");
z.setPlusFour("rawat");
Address a = new Address();
a.setId(1);
a.setZipCode(z);
try{
crudService.create(a);
}catch(Exception e){
log.info("exception occurs "+ e.getMessage());
}
}
}
我的CrudSrvice代码:
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class CrudServiceImpl implements CrudService {
@PersistenceContext(unitName = "localmedecube")
private EntityManager em;
public CrudServiceImpl() {
// TODO Auto-generated constructor stub
}
@Override
public <T> T create(T t) {
this.em.persist(t);
this.em.flush();
this.em.refresh(t);
return t;
}
@Override
public void delete(@SuppressWarnings("rawtypes") Class type, Object id) {
@SuppressWarnings("unchecked")
Object ref = this.em.getReference(type, id);
this.em.remove(ref);
}
@Override
public <T> T update(T t) {
return this.em.merge(t);
}
}
当我尝试保留我的地址实体时,它会给我这样的错误
引起:javax.persistence.PersistenceException:org.hibernate.PersistentObjectException:传递给的分离实体 persist:model.Address
请告诉我为什么会出现此异常。并为我提供适当的答案。
答案 0 :(得分:1)
如果您已使用Address
保留了id = 1
,那么您的代码就会中断。您必须为每个请求设置新的id
。
因为你已经使用
了@GeneratedValue(strategy = IDENTITY)
private long id;
数据库应该为您设置ID。对此的先决条件是将字段id
创建为自动增量字段。
例如,在MySQL
创建时设置自动增量字段。
CREATE TABLE Persons
(
id int NOT NULL AUTO_INCREMENT,
<...>
PRIMARY KEY (ID)
)