我在程序中 hibernate 了带注释的类。由于我正在运行一个 Spring 项目,我已将它们包含在 servlet.xml 文件中(com.student.dto 是实际的包名称),并在联系人实体上添加了 @Component 。有没有一种方法可以自动添加 @Component在所有的 hibernate 类上。每次我创建一个模型时,我最终都会这样做,并且觉得应该有更好的方法来做到这一点。
<context:component-scan base-package="com.student.dto" />
@Component
@Entity
@Table(name = "Contacts", catalog = "javadb")
public class ContactsDTO implements java.io.Serializable {
private int idContacts;
private StudentDTO StudentDTO;
private String addr1;
private String addr2;
private String city;
private String state;
private String pinCode;
private String country;
private String phone;
private String mobile;
private String email;
private String contactscol;
public ContactsDTO() {
}
public ContactsDTO(int idContacts) {
this.idContacts = idContacts;
}
public ContactsDTO(int idContacts, StudentDTO StudentDTO, String addr1,
String addr2, String city, String state, String pinCode,
String country, String phone, String mobile, String email,
String contactscol) {
this.idContacts = idContacts;
this.StudentDTO = StudentDTO;
this.addr1 = addr1;
this.addr2 = addr2;
this.city = city;
this.state = state;
this.pinCode = pinCode;
this.country = country;
this.phone = phone;
this.mobile = mobile;
this.email = email;
this.contactscol = contactscol;
}
getters & setters
最佳答案
你都做错了。 Spring Bean 默认情况下是单例的,您的实体不是线程安全的,也不应该是线程安全的。
实体应该是绑定(bind)到持久上下文的局部变量。它们不适合在多线程环境中访问。
并发控制为handled by the database你的应用程序逻辑应该主要关注 preventing lost updates通过application-level repeatable reads .
您的 DAO 和服务应该是 Spring 单例组件。您的实体和请求绑定(bind)的 DTO 永远不应该是单例的。这些对象的生命周期很短,其作用域仅限于生成它们的请求。
检查Spring Data JPA可靠的数据访问层设计的文档。
关于java - @Component Hibernate 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27081472/