什么是使用entitymanager的正确方法 [英] What is the right way to use entitymanager
问题描述
我在Jersey JAX-RS中有一个REST客户端,它接受请求,然后使用Hibernate的JPA实现从数据库中检索数据并返回一个JSON 。共享实体管理器,性能非常好,但如果有多个请求,我会从Hibernate中获得异常,主要是NullPointerException。
如果我使用实体管理器,没有任何例外,但性能较低。
处理EntityManager的正确方法是什么?
编辑:
在Albert的评论下面我用 EntityManagerHelper.java
并已更改entityManager引用使用EntityManagerHelper.getEntityManager()
例如
reqUser = entityManager.find(User.class,userId);
至
reqUser = EntityManagerHelper.getEntityManager()。find(User.class,userId);
编辑结束
Jersey.java
package local.domain;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path(/ testJersey)
public class Jersey {
static MainClass mainClass = new MainClass();
@GET
@Produces(application / json)
public Response getAccounts(@QueryParam(value =userId)final int userId){
String jsonString = mainClass.getAccounts(userId);
return Response.ok(jsonString,MediaType.APPLICATION_JSON).build();
// getJson
@Path(/ fields /)
@GET
@Produces(application / json)
public Response getAccountFields(@QueryParam(value =accountId)final int accountId){
String jsonString = mainClass.getAccountFields(accountId);
return Response.ok(jsonString,MediaType.APPLICATION_JSON).build();
} // getJson
}
MainClass.java
package local.domain;
导入javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import local.domain.pojos.Account;
import local.domain.pojos.User;
public class MainClass {
private EntityManagerFactory entityManagerFactory = null;
private EntityManager entityManager;
boolean sharedEntityManager = true;
public MainClass(){
entityManagerFactory = Persistence.createEntityManagerFactory(peristenceConfig);
entityManager = entityManagerFactory.createEntityManager();
}
public String getAccounts(int userId){
String result = null;
尝试{
User reqUser = null;
EntityManager entityManagerLocal = null;
if(sharedEntityManager)
reqUser = entityManager.find(User.class,userId);
else {
entityManagerLocal = entityManagerFactory.createEntityManager();
reqUser = entityManagerLocal.find(User.class,userId);
}
Gson gson = new GsonBuilder()。excludeFieldsWithoutExposeAnnotation()。create();
result = gson.toJson(reqUser);
if(!sharedEntityManager)
entityManagerLocal.close();
} catch(Exception exp){
System.err.println(UserId的异常+ userId);
exp.printStackTrace();
}
返回结果;
}
public String getAccountFields(int accountId){
String result = null;
尝试{
帐户reqAccount = null;
EntityManager entityManagerLocal = null;
if(sharedEntityManager)
reqAccount = entityManager.find(Account.class,accountId);
else {
entityManagerLocal = entityManagerFactory.createEntityManager();
reqAccount = entityManagerLocal.find(Account.class,accountId);
}
Gson gson = new GsonBuilder()。excludeFieldsWithoutExposeAnnotation()。create();
result = gson.toJson(reqAccount);
if(!sharedEntityManager)
entityManagerLocal.close();
} catch(Exception exp){
System.err.println(accountId的异常+ accountId);
exp.printStackTrace();
}
返回结果;
}
}
persistence.xml
<?xml version =1.0encoding =UTF-8?>
< persistence version =2.1xmlns =http://xmlns.jcp.org/xml/ns/persistencexmlns:xsi =http://www.w3.org/2001/XMLSchema-实例xsi:schemaLocation =http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd\">
< persistence-unit name =peristenceConfig>
< class> local.domain.pojos.Account< / class>
< class> local.domain.pojos.AccountField< / class>
< class> local.domain.pojos.User< / class>
<属性>
< property name =hibernate.connection.driver_classvalue =com.mysql.jdbc.Driver/>
< property name =hibernate.dialectvalue =org.hibernate.dialect.MySQLDialect/>
< property name =hibernate.show_sqlvalue =true/>
< property name =hibernate.connection.urlvalue =jdbc:mysql:// localhost / jpatest/>
< property name =hibernate.default_schemavalue =jpatest/>
< property name =hibernate.connection.usernamevalue =username/>
< property name =hibernate.connection.passwordvalue =password/>
< / properties>
< / persistence-unit>
< /余辉>
pom.xml
< project xmlns =http://maven.apache.org/POM/4.0.0xmlns:xsi =http://www.w3.org/2001/XMLSchema-instancexsi :schemaLocation =http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">
< modelVersion> 4.0.0< / modelVersion>
< groupId> Snippet< / groupId>
< artifactId> Snippet< / artifactId>
< version> 0.0.1-SNAPSHOT< / version>
<包装>战争< / packaging>
< build>
< sourceDirectory> src< / sourceDirectory>
< plugins>
< plugin>
< artifactId> maven-compiler-plugin< / artifactId>
< version> 3.5.1< / version>
<配置>
< source> 1.8< / source>
< target> 1.8< / target>
< / configuration>
< / plugin>
< plugin>
< artifactId> maven-war-plugin< / artifactId>
< version> 3.0.0< / version>
<配置>
< warSourceDirectory> WebContent< / warSourceDirectory>
< / configuration>
< / plugin>
< / plugins>
< / build>
<属性>
< jersey.version> 2.26-b02< / jersey.version>
< project.build.sourceEncoding> UTF-8< /project.build.sourceEncoding>
< / properties>
< dependencyManagement>
<依赖关系>
< dependency>
< groupId> org.glassfish.jersey< / groupId>
< artifactId> jersey-bom< / artifactId>
< version> $ {jersey.version}< / version>
< type> pom< / type>
< scope> import< / scope>
< /依赖关系>
< /依赖关系>
< / dependencyManagement>
< repositories>
< repository>
< id> JBoss存储库< / id>
< url> http://repository.jboss.org/nexus/content/groups/public/< / url>
< / repository>
< / repositories>
<依赖关系>
< dependency>
< groupId> org.glassfish.jersey.containers< / groupId>
< artifactId> jersey-container-servlet-core< / artifactId>
< /依赖关系>
< dependency>
< groupId> javax.ws.rs< / groupId>
< artifactId> jsr311-api< / artifactId>
< version> 1.1.1< / version>
< /依赖关系>
< dependency>
< groupId> org.hibernate.javax.persistence< / groupId>
< artifactId> hibernate-jpa-2.1-api< / artifactId>
< version> 1.0.0.Final< / version>
< /依赖关系>
< dependency>
< groupId> com.google.code.gson< / groupId>
< artifactId> gson< / artifactId>
< version> 2.8.0< / version>
< /依赖关系>
< dependency>
< groupId> mysql< / groupId>
< artifactId> mysql-connector-java< / artifactId>
< version> 5.1.6< / version>
< /依赖关系>
< dependency>
< groupId> org.hibernate< / groupId>
< artifactId> hibernate-core< / artifactId>
< version> 5.2.6.Final< / version>
< /依赖关系>
< /依赖关系>
< / project>
POJOs User.java Account.java AccountField.java
package local.domain.pojos;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.google.gson.annotations.Expose;
/ **
* tbl_account数据库表的持久类。
*
* /
@Entity
@Table(name =tbl_account)
@NamedQuery(name =Account.findAll,query =SELECT a FROM Account a)
public class Account实现Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name =account_id)
@Expose
@GeneratedValue(strategy = GenerationType.AUTO)
private int accountId;
@Column(name =account_status)
@Expose
private String accountStatus;
//与用户
的双向多对一关联@ManyToOne
@JoinColumn(name =user_id)
private用户tblUser;
//双向多对一关联到AccountField
@OneToMany(mappedBy =tblAccount)
@Expose
private List< AccountField> tblAccountFields;
$ b public Account(){
}
public int getAccountId(){
return this.accountId;
}
public void setAccountId(int accountId){
this.accountId = accountId;
}
public String getAccountStatus(){
return this.accountStatus;
}
public void setAccountStatus(String accountStatus){
this.accountStatus = accountStatus;
}
public User getTblUser(){
return this.tblUser;
}
public void setTblUser(User tblUser){
this.tblUser = tblUser;
}
公共列表< AccountField> getTblAccountFields(){
返回this.tblAccountFields;
}
public void setTblAccountFields(List< AccountField> tblAccountFields){
this.tblAccountFields = tblAccountFields;
}
public AccountField addTblAccountField(AccountField tblAccountField){
getTblAccountFields()。add(tblAccountField);
tblAccountField.setTblAccount(this);
返回tblAccountField;
}
public AccountField removeTblAccountField(AccountField tblAccountField){
getTblAccountFields()。remove(tblAccountField);
tblAccountField.setTblAccount(null);
返回tblAccountField;
}
}
package local.domain.pojos;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import com.google.gson.annotations.Expose;
/ **
* tbl_account_field数据库表的持久类。
*
* /
@Entity
@Table(name =tbl_account_field)
@NamedQuery(name =AccountField.findAll,query =SELECT a FROM AccountField a)
public class AccountField实现Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name =account_field_id)
@Expose
@GeneratedValue(strategy = GenerationType.AUTO)
private int accountFieldId;
@Column(name =account_field_label)
@Expose
private String accountFieldLabel;
//双向多对一关联账户
@ManyToOne
@JoinColumn(name =account_id)
私人账户tblAccount;
public AccountField(){
}
public int getAccountFieldId(){
return this.accountFieldId;
}
public void setAccountFieldId(int accountFieldId){
this.accountFieldId = accountFieldId;
}
public String getAccountFieldLabel(){
return this.accountFieldLabel;
}
public void setAccountFieldLabel(String accountFieldLabel){
this.accountFieldLabel = accountFieldLabel;
}
public Account getTblAccount(){
return this.tblAccount;
}
public void setTblAccount(Account tblAccount){
this.tblAccount = tblAccount;
}
}
package local.domain.pojos;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.google.gson.annotations.Expose;
/ **
* tbl_user数据库表的持久类。
*
* /
@Entity
@Table(name =tbl_user)
@NamedQuery(name =User.findAll,query =SELECT u FROM User u)
public class User实现Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name =user_id)
@Expose
@GeneratedValue(strategy = GenerationType.AUTO)
private int userId;
@Lob
@Column(name =user_email)
@Expose
private String userEmail;
@Column(name =user_last_login)
@Expose
私人时间戳userLastLogin;
@Column(name =user_name)
@Expose
private String userName;
//双向多对一关联至帐户
@OneToMany(mappedBy =tblUser)
@Expose
私人列表<帐户> tblAccounts;
$ b public User(){
}
public int getUserId(){
return this.userId;
}
public void setUserId(int userId){
this.userId = userId;
}
public String getUserEmail(){
return this.userEmail;
}
public void setUserEmail(String userEmail){
this.userEmail = userEmail;
}
public Timestamp getUserLastLogin(){
return this.userLastLogin;
}
public void setUserLastLogin(Timestamp userLastLogin){
this.userLastLogin = userLastLogin;
}
public String getUserName(){
return this.userName;
}
public void setUserName(String userName){
this.userName = userName;
}
公共列表<帐户> getTblAccounts(){
返回this.tblAccounts;
}
public void setTblAccounts(List< Account> tblAccounts){
this.tblAccounts = tblAccounts;
}
public account addTblAccount(Account tblAccount){
getTblAccounts()。add(tblAccount);
tblAccount.setTblUser(this);
返回tblAccount;
}
public account removeTblAccount(Account tblAccount){
getTblAccounts()。remove(tblAccount);
tblAccount.setTblUser(null);
返回tblAccount;
}
}
每种应用程序的正确方式可能有所不同。在你的情况下,我认为共享 EntityManager
会导致(你已经遇到的)不想要的行为。
我认为每个请求方法是一种安全的实现方式。另一种可能性是使用 ThreadLocal $ c $使用
EntityManager
每个 Thread
c>来管理这个,Spring就是这么做的。但这可能会让你的实现更复杂。
编辑:使用 I have a REST client in Jersey JAX-RS which takes requests and then using Hibernate's JPA implementation retrieves the data from the database and returns a JSON. Using a shared entity manager, the performance is quite good but if there are multiple requests, I get exceptions from Hibernate, mainly NullPointerException. If I use an entity manager per request I don't get any exceptions but the performance is lower. What is the proper way of handling the EntityManager? EDIT: Following Albert's comment below I have used EntityManagerHelper.java
and changed the entityManager references to use EntityManagerHelper.getEntityManager() e.g to EDIT end Below is the code I used. Jersey.java MainClass.java persistence.xml pom.xml POJOs User.java Account.java AccountField.java
The "correct" way might differ per type of application. In your case I think sharing the I think the per request approach is a safe way to implement. Another possibility is to use an EDIT: Also good to mention using 这篇关于什么是使用entitymanager的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! EntityManager $ c $在使用NIO时,在同一个
Thread
中处理多个请求时,可能会导致问题> > Thread
reqUser = entityManager.find(User.class, userId);
reqUser = EntityManagerHelper.getEntityManager().find(User.class, userId);
package local.domain;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/testJersey")
public class Jersey {
static MainClass mainClass = new MainClass();
@GET
@Produces("application/json")
public Response getAccounts(@QueryParam(value = "userId") final int userId) {
String jsonString = mainClass.getAccounts(userId);
return Response.ok(jsonString, MediaType.APPLICATION_JSON).build();
}// getJson
@Path("/fields/")
@GET
@Produces("application/json")
public Response getAccountFields(@QueryParam(value = "accountId") final int accountId) {
String jsonString = mainClass.getAccountFields(accountId);
return Response.ok(jsonString, MediaType.APPLICATION_JSON).build();
}// getJson
}
package local.domain;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import local.domain.pojos.Account;
import local.domain.pojos.User;
public class MainClass {
private EntityManagerFactory entityManagerFactory = null;
private EntityManager entityManager;
boolean sharedEntityManager = true;
public MainClass() {
entityManagerFactory = Persistence.createEntityManagerFactory("peristenceConfig");
entityManager = entityManagerFactory.createEntityManager();
}
public String getAccounts(int userId) {
String result = null;
try {
User reqUser = null;
EntityManager entityManagerLocal = null;
if (sharedEntityManager)
reqUser = entityManager.find(User.class, userId);
else {
entityManagerLocal = entityManagerFactory.createEntityManager();
reqUser = entityManagerLocal.find(User.class, userId);
}
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
result = gson.toJson(reqUser);
if (!sharedEntityManager)
entityManagerLocal.close();
} catch (Exception exp) {
System.err.println("Exception with userId"+userId);
exp.printStackTrace();
}
return result;
}
public String getAccountFields(int accountId) {
String result = null;
try {
Account reqAccount = null;
EntityManager entityManagerLocal = null;
if (sharedEntityManager)
reqAccount = entityManager.find(Account.class, accountId);
else {
entityManagerLocal = entityManagerFactory.createEntityManager();
reqAccount = entityManagerLocal.find(Account.class, accountId);
}
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
result = gson.toJson(reqAccount);
if (!sharedEntityManager)
entityManagerLocal.close();
} catch (Exception exp) {
System.err.println("Exception with accountId"+accountId);
exp.printStackTrace();
}
return result;
}
}
<?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://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="peristenceConfig">
<class>local.domain.pojos.Account</class>
<class>local.domain.pojos.AccountField</class>
<class>local.domain.pojos.User</class>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.connection.url" value="jdbc:mysql://localhost/jpatest" />
<property name="hibernate.default_schema" value="jpatest" />
<property name="hibernate.connection.username" value="username" />
<property name="hibernate.connection.password" value="password" />
</properties>
</persistence-unit>
</persistence>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Snippet</groupId>
<artifactId>Snippet</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<jersey.version>2.26-b02</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<repositories>
<repository>
<id>JBoss repository</id>
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.6.Final</version>
</dependency>
</dependencies>
</project>
package local.domain.pojos;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.google.gson.annotations.Expose;
/**
* The persistent class for the tbl_account database table.
*
*/
@Entity
@Table(name="tbl_account")
@NamedQuery(name="Account.findAll", query="SELECT a FROM Account a")
public class Account implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="account_id")
@Expose
@GeneratedValue(strategy = GenerationType.AUTO)
private int accountId;
@Column(name="account_status")
@Expose
private String accountStatus;
//bi-directional many-to-one association to User
@ManyToOne
@JoinColumn(name="user_id")
private User tblUser;
//bi-directional many-to-one association to AccountField
@OneToMany(mappedBy="tblAccount")
@Expose
private List<AccountField> tblAccountFields;
public Account() {
}
public int getAccountId() {
return this.accountId;
}
public void setAccountId(int accountId) {
this.accountId = accountId;
}
public String getAccountStatus() {
return this.accountStatus;
}
public void setAccountStatus(String accountStatus) {
this.accountStatus = accountStatus;
}
public User getTblUser() {
return this.tblUser;
}
public void setTblUser(User tblUser) {
this.tblUser = tblUser;
}
public List<AccountField> getTblAccountFields() {
return this.tblAccountFields;
}
public void setTblAccountFields(List<AccountField> tblAccountFields) {
this.tblAccountFields = tblAccountFields;
}
public AccountField addTblAccountField(AccountField tblAccountField) {
getTblAccountFields().add(tblAccountField);
tblAccountField.setTblAccount(this);
return tblAccountField;
}
public AccountField removeTblAccountField(AccountField tblAccountField) {
getTblAccountFields().remove(tblAccountField);
tblAccountField.setTblAccount(null);
return tblAccountField;
}
}
package local.domain.pojos;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import com.google.gson.annotations.Expose;
/**
* The persistent class for the tbl_account_field database table.
*
*/
@Entity
@Table(name="tbl_account_field")
@NamedQuery(name="AccountField.findAll", query="SELECT a FROM AccountField a")
public class AccountField implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="account_field_id")
@Expose
@GeneratedValue(strategy = GenerationType.AUTO)
private int accountFieldId;
@Column(name="account_field_label")
@Expose
private String accountFieldLabel;
//bi-directional many-to-one association to Account
@ManyToOne
@JoinColumn(name="account_id")
private Account tblAccount;
public AccountField() {
}
public int getAccountFieldId() {
return this.accountFieldId;
}
public void setAccountFieldId(int accountFieldId) {
this.accountFieldId = accountFieldId;
}
public String getAccountFieldLabel() {
return this.accountFieldLabel;
}
public void setAccountFieldLabel(String accountFieldLabel) {
this.accountFieldLabel = accountFieldLabel;
}
public Account getTblAccount() {
return this.tblAccount;
}
public void setTblAccount(Account tblAccount) {
this.tblAccount = tblAccount;
}
}
package local.domain.pojos;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.google.gson.annotations.Expose;
/**
* The persistent class for the tbl_user database table.
*
*/
@Entity
@Table(name="tbl_user")
@NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="user_id")
@Expose
@GeneratedValue(strategy = GenerationType.AUTO)
private int userId;
@Lob
@Column(name="user_email")
@Expose
private String userEmail;
@Column(name="user_last_login")
@Expose
private Timestamp userLastLogin;
@Column(name="user_name")
@Expose
private String userName;
//bi-directional many-to-one association to Account
@OneToMany(mappedBy="tblUser")
@Expose
private List<Account> tblAccounts;
public User() {
}
public int getUserId() {
return this.userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserEmail() {
return this.userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public Timestamp getUserLastLogin() {
return this.userLastLogin;
}
public void setUserLastLogin(Timestamp userLastLogin) {
this.userLastLogin = userLastLogin;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public List<Account> getTblAccounts() {
return this.tblAccounts;
}
public void setTblAccounts(List<Account> tblAccounts) {
this.tblAccounts = tblAccounts;
}
public Account addTblAccount(Account tblAccount) {
getTblAccounts().add(tblAccount);
tblAccount.setTblUser(this);
return tblAccount;
}
public Account removeTblAccount(Account tblAccount) {
getTblAccounts().remove(tblAccount);
tblAccount.setTblUser(null);
return tblAccount;
}
}
EntityManager
will cause (what you are already experiencing) unwanted behavior.EntityManager
per Thread
, using a ThreadLocal
to manage this, this is how Spring does it. But this might make your implementation more complex.EntityManager
per Thread
can cause issues when using NIO, processing multiple requests within the same Thread
.